﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ErrorCodeInfo;
using HalconDotNet;
using log4net;

namespace DimensionalMeasurement
{
    public class Tool
    {
        /// <summary>
        /// 上下拼接图片
        /// </summary>
        /// <param name="ho_Image"></param>
        /// <param name="ho_Image1"></param>
        /// <param name="ho_Image2"></param>
        /// <param name="ho_Image3"></param>
        /// <param name="ho_TiledImage2"></param>
        public static HObject ImageIstitching(HObject ho_Image, HObject ho_Image1, HObject ho_Image2 = null, HObject ho_Image3 = null)
        {
            HObject ho_ObjectsConcat, ho_ObjectsConcat1, ho_TiledImage;
            HObject ho_TiledImage1, ho_ObjectsConcat2;

            HTuple hv_Width = null, hv_Height = null, hv_Width1 = null;
            HTuple hv_Height1 = null, hv_Width2 = null, hv_Height2 = null;
            HTuple hv_Width3 = null, hv_Height3 = null; HTuple hv_Width4 = null, hv_Height4 = null;
            HOperatorSet.GenEmptyObj(out ho_ObjectsConcat);
            HOperatorSet.GenEmptyObj(out ho_ObjectsConcat1);
            HOperatorSet.GenEmptyObj(out ho_TiledImage);
            HOperatorSet.GenEmptyObj(out ho_TiledImage1);
            HOperatorSet.GenEmptyObj(out ho_ObjectsConcat2);

            HOperatorSet.GetImageSize(ho_Image, out hv_Width, out hv_Height);
            HOperatorSet.GetImageSize(ho_Image1, out hv_Width1, out hv_Height1);

            ho_ObjectsConcat.Dispose();
            HOperatorSet.ConcatObj(ho_Image, ho_Image1, out ho_ObjectsConcat);
            ho_TiledImage.Dispose();
            HOperatorSet.TileImagesOffset(ho_ObjectsConcat, out ho_TiledImage, (new HTuple(0)).TupleConcat(
                hv_Height), (new HTuple(0)).TupleConcat(0), (new HTuple(-1)).TupleConcat(-1), (new HTuple(-1)).TupleConcat(
                -1), (new HTuple(-1)).TupleConcat(-1), (new HTuple(-1)).TupleConcat(-1),
                hv_Width, hv_Height + hv_Height1);

            if (ho_Image2 != null)
            {
                HOperatorSet.GetImageSize(ho_Image2, out hv_Width2, out hv_Height2);
                HOperatorSet.GetImageSize(ho_Image3, out hv_Width3, out hv_Height3);
                ho_ObjectsConcat1.Dispose();
                HOperatorSet.ConcatObj(ho_Image2, ho_Image3, out ho_ObjectsConcat1);
                ho_TiledImage1.Dispose();
                HOperatorSet.TileImagesOffset(ho_ObjectsConcat1, out ho_TiledImage1, (new HTuple(0)).TupleConcat(
                    hv_Height2), (new HTuple(0)).TupleConcat(0), (new HTuple(-1)).TupleConcat(-1), (new HTuple(-1)).TupleConcat(
                    -1), (new HTuple(-1)).TupleConcat(-1), (new HTuple(-1)).TupleConcat(-1),
                    hv_Width2, hv_Height2 + hv_Height3);

                ho_ObjectsConcat2.Dispose();
                HOperatorSet.ConcatObj(ho_TiledImage, ho_TiledImage1, out ho_ObjectsConcat2);
                HOperatorSet.TileImagesOffset(ho_ObjectsConcat2, out ho_TiledImage, (new HTuple(0)).TupleConcat(
                    0), (new HTuple(0)).TupleConcat(hv_Width), (new HTuple(-1)).TupleConcat(-1), (new HTuple(-1)).TupleConcat(
                    -1), (new HTuple(-1)).TupleConcat(-1), (new HTuple(-1)).TupleConcat(-1),
                    hv_Width + hv_Width2, hv_Height + hv_Height2);
                ho_Image2.Dispose();
                ho_Image3.Dispose();
            }
            ho_Image.Dispose();
            ho_Image1.Dispose();
            ho_ObjectsConcat.Dispose();
            ho_ObjectsConcat1.Dispose();
            ho_TiledImage1.Dispose();
            ho_ObjectsConcat2.Dispose();
            return ho_TiledImage;

        }

        #region 窗体移动
        //点击窗口左上角那个图标时的系统信息
        private const int WM_SYSCOMMAND = 0x0112;
        //移动信息
        private const int SC_MOVE = 0xF010;
        //表示鼠标在窗口标题栏时的系统信息
        private const int HTCAPTION = 0x0002;
        //鼠标在窗体客户区（除了标题栏和边框以外的部分）时发送的消息
        private const int WM_NCHITTEST = 0x84;
        //表示鼠标在窗口客户区的系统消息
        private const int HTCLIENT = 0x1;
        //最大化信息
        private const int SC_MAXIMIZE = 0xF030;
        //最小化信息
        private const int SC_MINIMIZE = 0xF020;

        //释放鼠标焦点捕获，这样就不会再发出WM_NCHITTEST消息
        [DllImport("user32.dll")]
        private static extern bool ReleaseCapture();

        //向当前窗体发送消息
        [DllImport("user32.dll")]
        private static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);

        public static void FormMove(IntPtr hwnd)
        {
            ReleaseCapture();
            //向当前窗体发送 移动+表示鼠标在标题栏上 消息
            SendMessage(hwnd, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
        }
        #endregion

        #region 日志相关

        public static readonly ILog lognegative = LogManager.GetLogger("lognegative");//这里的 lognegative 和 log4net.config 里的名字要一样
        public static readonly ILog logpositive = LogManager.GetLogger("logpositive");//这里的 logpositive 和 log4net.config 里的名字要一样

        public static void WriteNegativeLog(string info)
        {
            if (lognegative.IsInfoEnabled)
            {
                lognegative.Info(info);
            }
        }
        public static void WritePositiveLog(string info)
        {
            if (logpositive.IsInfoEnabled)
            {
                logpositive.Info(info);
            }
        }





        /// <summary>
        /// 记录窗体错误日志
        /// </summary>
        /// <param name="strMsg"></param>
        public static void LogForm(Exception ex)
        {
            string str = ex.StackTrace.Replace("Halcon", "GS").Replace("HALCON", "GS").Replace("HOperatorSet", "GS").Replace("(HObject", "GSObject").Replace("HTuple", "GSTuple");
            WriteLine("[" + DateTime.Now.ToString() + "]" + $"{ErrorCode.ReportError(ex)},{str}", "窗体日志");
        }
        /// <summary>
        /// 记录窗体错误日志
        /// </summary>
        /// <param name="strMsg"></param>
        public static void LogForm(string strMsg)
        {
            string str = strMsg.Replace("Halcon", "GS").Replace("HALCON", "GS").Replace("HOperatorSet", "GS").Replace("(HObject", "GSObject").Replace("HTuple", "GSTuple");
            WriteLine("[" + DateTime.Now.ToString() + "]" + str, "窗体日志");
        }
        /// <summary>
        /// 负极记录耗时日志 
        /// </summary>
        /// <param name="strMsg"></param>
        public static void LogWriteN(string strMsg)
        {
            WriteLine(/*"[" + DateTime.Now.ToString("HH:mm:ss.fff") + "]" + */strMsg, "负极图像处理耗时");
        }
        /// <summary>
        /// 正极记录耗时日志 
        /// </summary>
        /// <param name="strMsg"></param>
        public static void LogWriteP(string strMsg)
        {
            WriteLine(/*"[" + DateTime.Now.ToString("HH:mm:ss.fff") + "]" + */strMsg, "正极图像处理耗时");
        }
        /// <summary>
        /// 参数修改日志
        /// </summary>
        /// <param name="strMsg"></param>
        public static void LogParameterUpdate(string strMsg)
        {
            WriteLine("[" + DateTime.Now.ToString() + "]" + strMsg, "参数修改日志");
        }

        /// <summary>
        /// 系统运行日志
        /// </summary>
        /// <param name="strMsg"></param>
        public static void LogSystemRuning(string strMsg)
        {
            WriteLine("[" + DateTime.Now.ToString() + "]" + strMsg, "系统运行日志");
        }
        public static void WriteLine(string strLog, string _filename)
        {
            // 日志文件名称：log_20090101.log
            string strFileName = System.DateTime.Now.ToString("yyyyMMdd") + _filename + ".log";
            if (strLog != "")
            {
                // 相对路径：根目录log文件夹下，如果目标文件夹不存在则创建一个
                string strPath = "";
                if (PublicSet.Myset.PathLog == "" || PublicSet.Myset.PathLog == null)
                {
                    strPath = AppDomain.CurrentDomain.BaseDirectory + "\\log日志\\" + DateTime.Now.ToString("yyyyMMdd");
                }
                else
                {
                    strPath = PublicSet.Myset.PathLog + "\\log日志\\" + DateTime.Now.ToString("yyyyMMdd");
                }
                if (!Directory.Exists(strPath)) { Directory.CreateDirectory(strPath); }
                // 文件名
                strPath = strPath + "\\" + strFileName;
                // 写日志记录
                try
                {
                    // 如果文件存在则追加记录，如果文件不存在则创建并写入记录
                    System.IO.StreamWriter objSw = new StreamWriter(strPath, true);
                    objSw.WriteLine(strLog);
                    objSw.Flush();
                    objSw.Close();
                }
                catch { }
            }
        }
        #endregion

        #region 自动删除相关
        public static string pathSplit(string path)
        {
            try
            {
                string[] str = path.Split('\\');
                return path = str[0] + "\\" + str[1];
            }
            catch (Exception)
            {
                return "";
            }

        }
        /// <summary>
        /// 删除空的文件夹
        /// </summary>
        /// <param name="path"></param>
        public static void Delete(string path)
        {
            if (!Directory.Exists(path))
            {
                return;
            }
            string[] directories = Directory.GetDirectories(path);
            string[] files = Directory.GetFiles(path);

            if (directories.Length == 0 && files.Length == 0)
            {
                Directory.Delete(path);
                return;
            }
            foreach (string directorie in directories)
            {
                Delete(directorie);
            }
        }



        /// <summary>
        /// 删除指定目录下超过指定存储天数的文件
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="day">存储天数</param>
        public static void FileDelete1(string path, int day)
        {

            if (!Directory.Exists(path))
            {
                return;
            }
            string[] directories = Directory.GetDirectories(path);
            string[] files = Directory.GetFiles(path);
            if (directories.Length == 0 && files.Length == 0)
            {
                Directory.Delete(path);
                return;
            }
            foreach (string directorie in directories)
            {
                FileDelete1(directorie, day);
            }
            foreach (string file in files)
            {
                if ((DateTime.Now - new FileInfo(file).CreationTime).Days >= day)
                {
                    File.Delete(file);
                    LogForm("自动删除数据结束   地址：" + file);
                }
            }
        }
        /// <summary>
        /// 删除指定目录下超过指定存储天数的文件夹
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="day">存储天数</param>
        public static void FileDelete(string path, int day)
        {
            try
            {
                for (int i = 0; i < 5; i++)
                {
                    DateTime time = DateTime.Now.AddDays(-day - i);
                    string strPath = path.Replace("yyyy", time.ToString("yyyy")).Replace("MM", time.ToString("MM")).Replace("dd", time.ToString("dd")).Replace("WS", PublicSet.Myset.WorkingShift).Replace("NorP", "负极").Replace("Line", PublicSet.Cameraset.LineID).Replace("Machine", PublicSet.Cameraset.MachineID).Replace("PoleReel", PublicSet.Myset.PoleReelN);
                    if (Directory.Exists(strPath))
                    {
                        DirectoryInfo item = new DirectoryInfo(strPath);
                        TimeSpan ts = DateTime.Now - item.LastWriteTime;
                        if (ts.Days >= day)
                        {
                            item.Delete(true);
                            LogForm("自动删除图片结束   地址：" + strPath);
                        }
                    }
                    strPath = path.Replace("yyyy", time.ToString("yyyy")).Replace("MM", time.ToString("MM")).Replace("dd", time.ToString("dd")).Replace("WS", PublicSet.Myset.WorkingShift).Replace("NorP", "正极").Replace("Line", PublicSet.Cameraset.LineID).Replace("Machine", PublicSet.Cameraset.MachineID).Replace("PoleReel", PublicSet.Myset.PoleReelP);
                    if (Directory.Exists(strPath))
                    {
                        DirectoryInfo item = new DirectoryInfo(strPath);
                        TimeSpan ts = DateTime.Now - item.LastWriteTime;
                        if (ts.Days >= day)
                        {
                            item.Delete(true);
                            LogForm("自动删除图片结束   地址：" + strPath);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogForm("删除文件失败" + ex.ToString());
            }
        }
        /// <summary>
        /// 删除指定目录下超过指定存储天数的日志
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="day">存储天数</param>
        public static void LogDelete(string path, int day)
        {
            if (!Directory.Exists(path))
            {
                return;
            }
            try
            {
                DirectoryInfo TheFolder = new DirectoryInfo(path);
                //遍历文件
                foreach (DirectoryInfo NextFile in TheFolder.GetDirectories())
                {
                    TimeSpan ts = DateTime.Now - NextFile.LastWriteTime;
                    if (ts.Days >= day)
                    {
                        NextFile.Delete(true);
                    }
                }
            }
            catch (Exception ex)
            {
                LogForm("删除LOG日志失败" + ex.ToString());
            }
        }
        #endregion
        public static string Replace(string s, string workingShift, string NorP, string Line, string Machine, string PoleReelID = "", string ID = "", string NGType = "")
        {
            DateTime time = new DateTime();
            if (s.Contains("WS"))
            {
                //如果存图路径中有按班次存图，就使用按班次得到的时间，主要是区分夜班凌晨时间
                time = PublicSet.TimeNow;
            }
            else
            {
                time = DateTime.Now;
            }
            return s.Replace("yyyy", time.ToString("yyyy")).Replace("MM", time.ToString("MM")).Replace("dd", time.ToString("dd")).Replace("HH", time.ToString("HH")).Replace("mm", time.ToString("mm")).Replace("ss", time.ToString("ss")).Replace("fff", time.ToString("fff")).Replace("WS", workingShift).Replace("NorP", NorP).Replace("Line", Line).Replace("Machine", Machine).Replace("ID", ID).Replace("PoleReel", PoleReelID).Replace("NGType", NGType);
        }

        public static string Replace_Yesterday(string s, string workingShift, string NorP, string Line, string Machine, string PoleReelID = "", string ID = "")
        {
            DateTime time = DateTime.Now.AddDays(-1);
            return s.Replace("yyyy", time.ToString("yyyy")).Replace("MM", time.ToString("MM")).Replace("dd", time.ToString("dd")).Replace("HH", time.ToString("HH")).Replace("mm", time.ToString("mm")).Replace("ss", time.ToString("ss")).Replace("fff", time.ToString("fff")).Replace("WS", workingShift).Replace("NorP", NorP).Replace("Line", Line).Replace("Machine", Machine).Replace("ID", ID).Replace("PoleReel", PoleReelID);
        }


        public static string Replace_TJ_Hour(string s, DateTime time, string workingShift, string NorP, string Line, string Machine, string PoleReelID = "", string ID = "")
        {
            return s.Replace("yyyy", time.ToString("yyyy")).Replace("MM", time.ToString("MM")).Replace("dd", time.ToString("dd")).Replace("HH", time.ToString("HH")).Replace("mm", time.ToString("mm")).Replace("ss", time.ToString("ss")).Replace("fff", time.ToString("fff")).Replace("WS", workingShift).Replace("NorP", NorP).Replace("Line", Line).Replace("Machine", Machine).Replace("ID", ID).Replace("PoleReel", PoleReelID);
        }


        /// <summary>
        /// 删除图片使用
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        //public static string Replace(string s)
        //{

        //    s = s.Remove(s.IndexOf("yyyy-MM-dd")) + "yyyy-MM-dd";
        //    return s.Replace("yyyy", DateTime.Now.ToString("yyyy")).Replace("MM", DateTime.Now.ToString("MM")).Replace("dd", DateTime.Now.ToString("dd")).Replace("WS", "").Replace("NorP", "");
        //}


        #region 存储数据相关

        /// <summary>
        /// 正极生产数据路径
        /// </summary>
        static string ProductionFileNameP = "";
        /// <summary>
        /// 负极生产数据路径
        /// </summary>
        static string ProductionFileNameN = "";

        ///// <summary>
        ///// 正极生产数据路径-王博要的
        ///// </summary>
        //static string ProductionFileNameP_W = "";
        ///// <summary>
        ///// 负极生产数据路径-王博要的
        ///// </summary>
        //static string ProductionFileNameN_W = "";
        ///// <summary>
        ///// 正极写入生产数据流-王博要的
        ///// </summary>
        //static StreamWriter swP_W;
        ///// <summary>
        ///// 负极写入生产数据流-王博要的
        ///// </summary>
        //static StreamWriter swN_W;
        ///// <summary>
        ///// 正极是否打开生产数据流-王博要的
        ///// </summary>
        //static bool bP_W = true;
        ///// <summary>
        ///// 负极是否打开生产数据流-王博要的
        ///// </summary>
        //static bool bN_W = true;

        /// <summary>
        /// 正极MES数据路径
        /// </summary>
        static string MESFileNameP = "";
        /// <summary>
        /// 负极MES数据路径
        /// </summary>
        static string MESFileNameN = "";



        /// <summary>
        /// CSV数据流
        /// </summary>
        static StreamWriter sw;

        public Stopwatch sp = new Stopwatch();
        /// <summary>
        /// 正极写入生产数据流
        /// </summary>
        static StreamWriter swP;
        /// <summary>
        /// 负极写入生产数据流
        /// </summary>
        static StreamWriter swN;
        /// <summary>
        ///初始路径： "E:尺寸检测数据"
        /// </summary>
        static private string foldPath = "E:尺寸检测数据";
        /// <summary>
        /// 正极是否打开生产数据流
        /// </summary>
        static bool bP = true;
        /// <summary>
        /// 负极是否打开生产数据流
        /// </summary>
        static bool bN = true;

        /// <summary>
        /// 统计数据NG-尾卷正极
        /// </summary>
        static string TJ_NG_WeiJuanP;
        /// <summary>
        /// 统计数据NG-尾卷负极
        /// </summary>
        static string TJ_NG_WeiJuanN;

        /// <summary>
        /// 统计数据NG-尾卷负极-123
        /// </summary>
        public static string TJ_NG_WeiJuanN_123;


        /// <summary>
        /// 统计数据NG-班次优先级正极
        /// </summary>
        static string TJ_NG_BanCiP_Priority;
        /// <summary>
        /// 统计数据NG-班次优先级负极
        /// </summary>
        static string TJ_NG_BanCiN_Priority;


        /// <summary>
        /// 统计数据NG-分时（每小时）优先级正极
        /// </summary>
        public static string TJ_NG_HourP_Priority;
        /// <summary>
        /// 统计数据NG-分时（每小时）优先级负极
        /// </summary>
        public static string TJ_NG_HourN_Priority;


        /// 统计数据NG-班次正极
        /// </summary>
        static string TJ_NG_BanCiP;
        /// <summary>
        /// 统计数据NG-班次负极
        /// </summary>
        static string TJ_NG_BanCiN;
        /// <summary>
        /// 白夜班
        /// </summary>
        string MornOrNight;
        /// <summary>
        /// 片位数据NG-百片正极
        /// </summary>
        static string PW_NG_BaiPianP;
        /// <summary>
        /// 片位数据NG-百片负极
        /// </summary>
        static string PW_NG_BaiPianN;
        /// <summary>
        /// 创建csv数据表头
        /// </summary>       
        public static bool CreateCSV()
        {
            string MornOrNight = "";

            int MorningResult = DateTime.Compare(DateTime.Now, Convert.ToDateTime(PublicSet.Myset.Morn));
            int NightResult = DateTime.Compare(DateTime.Now, Convert.ToDateTime(PublicSet.Myset.Night));
            try
            {
                StreamWriter sw1;
                FileStream fs;
                #region 生产数据路径                              
                if (MorningResult == -1 && NightResult == -1)//凌晨时间为前一天夜班
                {
                    PublicSet.TimeNow = DateTime.Now.AddDays(-1);
                    MornOrNight = "晚班";
                    ProductionFileNameN = Replace_Yesterday(PublicSet.Myset.SCDataSava, MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN) + "\\" + Replace_Yesterday(PublicSet.Myset.SCName, MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN) + ".csv";

                    ProductionFileNameP = Replace_Yesterday(PublicSet.Myset.SCDataSava, MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP) + "\\" + Replace_Yesterday(PublicSet.Myset.SCName, MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP) + ".csv";

                    //判断是否存在正极表格，不存在则生成
                    if (!Directory.Exists(Replace_Yesterday(PublicSet.Myset.SCDataSava, MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP)))
                    {
                        Directory.CreateDirectory(Replace_Yesterday(PublicSet.Myset.SCDataSava, MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP));
                    }
                    //判断是否存在负极表格，不存在则生成
                    if (!Directory.Exists(Replace_Yesterday(PublicSet.Myset.SCDataSava, MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN)))
                    {
                        Directory.CreateDirectory(Replace_Yesterday(PublicSet.Myset.SCDataSava, MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN));
                    }


                }
                if (MorningResult == 1 && NightResult == 1 || NightResult == 0)//当天夜班并非凌晨
                {
                    PublicSet.TimeNow = DateTime.Now;
                    MornOrNight = "晚班";
                    ProductionFileNameN = Replace(PublicSet.Myset.SCDataSava, MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN) + "\\" + Replace(PublicSet.Myset.SCName, "晚班", "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN) + ".csv";

                    ProductionFileNameP = Replace(PublicSet.Myset.SCDataSava, MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP) + "\\" + Replace(PublicSet.Myset.SCName, "晚班", "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP) + ".csv";

                    if (!Directory.Exists(Replace(PublicSet.Myset.SCDataSava, MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP)))
                    {
                        Directory.CreateDirectory(Replace(PublicSet.Myset.SCDataSava, MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP));
                    }
                    if (!Directory.Exists(Replace(PublicSet.Myset.SCDataSava, MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN)))
                    {
                        Directory.CreateDirectory(Replace(PublicSet.Myset.SCDataSava, MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN));
                    }


                }
                if ((MorningResult == 1 && NightResult == -1) || MorningResult == 0)//当天白班
                {
                    PublicSet.TimeNow = DateTime.Now;
                    MornOrNight = "白班";
                    ProductionFileNameN = Replace(PublicSet.Myset.SCDataSava, MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN) + "\\" + Replace(PublicSet.Myset.SCName, "白班", "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN) + ".csv";

                    ProductionFileNameP = Replace(PublicSet.Myset.SCDataSava, MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP) + "\\" + Replace(PublicSet.Myset.SCName, "白班", "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP) + ".csv";

                    if (!Directory.Exists(Replace(PublicSet.Myset.SCDataSava, MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP)))
                    {
                        Directory.CreateDirectory(Replace(PublicSet.Myset.SCDataSava, MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP));
                    }
                    if (!Directory.Exists(Replace(PublicSet.Myset.SCDataSava, MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN)))
                    {
                        Directory.CreateDirectory(Replace(PublicSet.Myset.SCDataSava, MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN));
                    }

                }

                //白夜班生产数据
                if (!File.Exists(ProductionFileNameN) || !File.Exists(ProductionFileNameP))
                {
                    //  string BoxHead = "时间,产品ID,线体编号,设备编号,工位,极卷ID,V角深度纠偏,V角宽度纠偏,正负极,白夜班,检测结果,不良类型,极片头长,极片尾长,极片头宽,极片尾宽,左肩宽,右肩宽,极耳宽,极耳高,陶瓷高/带料高,极耳打折,涂布高,极片总长,左上垂直度,右上垂直度,左下垂直度,右下垂直度,左上缺角面积,右上缺角面积,左下缺角面积,右下缺角面积,左上V角度,左上V宽度,左上V深度,右上V角度,右上V宽度,右上V深度,左下V角度,左下V宽度,左下V深度,右下V角度,右下V宽度,右下V深度,极片偏移-皮带方向,极片偏移-非皮带方向,极片偏移-角度";

                    //负极白夜班生产数据
                    if (!File.Exists(ProductionFileNameN))
                    {
                        try
                        {


                            string BoxHead = $"时间,产品ID,线体编号,设备编号,正负极,工位,极卷ID,V角深度纠偏,V角宽度纠偏,白夜班,检测结果,不良类型,NG分类,{PublicSet.Myset.NJPHeadLengthName + PublicSet.Myset.NJPHeadLengthRange.Trim('：')},{PublicSet.Myset.NJPTailLengthName + PublicSet.Myset.NJPHeadWidthRange.Trim('：')},{PublicSet.Myset.NJPHeadWidthName + PublicSet.Myset.NJPHeadWidthRange.Trim('：')},{PublicSet.Myset.NJPTailWidthName + PublicSet.Myset.NJPTailWidthRange.Trim('：')},{PublicSet.Myset.NJELeftShoulderName + PublicSet.Myset.NJELeftShoulderRange.Trim('：')},{PublicSet.Myset.NJERightShoulderName + PublicSet.Myset.NJERightShoulderRange.Trim('：')},{PublicSet.Myset.NJEWidthName + PublicSet.Myset.NJEWidthRange.Trim('：')},{PublicSet.Myset.NJEHeightName + PublicSet.Myset.NJEHeightRange.Trim('：')},{PublicSet.Myset.NDLHeightName + PublicSet.Myset.NDLHeightRange.Trim('：')},极耳余料,极耳打折,{PublicSet.Myset.NJPCoatingName + PublicSet.Myset.NJPCoatingRange.Trim('：')},{PublicSet.Myset.NJPTotalWidthName + PublicSet.Myset.NJPTotalWidthRange.Trim('：')},{PublicSet.Myset.NLeftUpAngleName + PublicSet.Myset.NLeftUpAngleRange.Trim('：')},{PublicSet.Myset.NRightUpAngleName + PublicSet.Myset.NRightUpAngleRange.Trim('：')},{PublicSet.Myset.NLeftDownAngleName + PublicSet.Myset.NLeftDownAngleRange.Trim('：')},{PublicSet.Myset.NRightDownAngleName + PublicSet.Myset.NRightDownAngleRange.Trim('：')},{PublicSet.Myset.NLeftUpBevelName + PublicSet.Myset.NLeftUpBevelRange},{PublicSet.Myset.NRightUpBevelName + PublicSet.Myset.NRightUpBevelRange},{PublicSet.Myset.NLeftDownBevelName + PublicSet.Myset.NLeftDownBevelRange},{PublicSet.Myset.NRightDownBevelName + PublicSet.Myset.NRightDownBevelRange},{PublicSet.Myset.NLeftUpVAngleName + PublicSet.Myset.NLeftUpVAngleRange.Trim('：')},{PublicSet.Myset.NLeftUpVWidthName + PublicSet.Myset.NLeftUpVWidthRange.Trim('：')},{PublicSet.Myset.NLeftUpVDepthName + PublicSet.Myset.NLeftUpVDepthRange.Trim('：')},{PublicSet.Myset.NRightUpVAngleName + PublicSet.Myset.NRightUpVAngleRange.Trim('：')},{PublicSet.Myset.NRightUpVWidthName + PublicSet.Myset.NRightUpVWidthRange.Trim('：')},{PublicSet.Myset.NRightUpVDepthName + PublicSet.Myset.NRightUpVDepthRange.Trim('：')},{PublicSet.Myset.NLeftDownVAngleName + PublicSet.Myset.NLeftDownVAngleRange.Trim('：')},{PublicSet.Myset.NLeftDownVWidthName + PublicSet.Myset.NLeftDownVWidthRange.Trim('：')},{PublicSet.Myset.NLeftDownVDepthName + PublicSet.Myset.NLeftDownVDepthRange.Trim('：')},{PublicSet.Myset.NRightDownVAngleName + PublicSet.Myset.NRightDownVAngleRange.Trim('：')},{PublicSet.Myset.NRightDownVWidthName + PublicSet.Myset.NRightDownVWidthRange.Trim('：')},{PublicSet.Myset.NRightDownVDepthName + PublicSet.Myset.NRightDownVDepthRange.Trim('：')},极片偏移-皮带方向,极片偏移-非皮带方向,极片偏移-角度,左上MarkX,左上MarkY,右上MarkX,右上MarkY,左下MarkX,左下MarkY,右下MarkX,右下MarkY,Time";
                            fs = new FileStream(ProductionFileNameN, FileMode.Create, FileAccess.Write);
                            sw1 = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                            sw1.WriteLine(BoxHead);
                            sw1.Flush();
                            sw1.Close();
                            fs.Close();
                            fs.Dispose();
                            bN = true;
                        }
                        catch (Exception)
                        {

                        }
                    }

                    //正极白夜班生产数据
                    if (!File.Exists(ProductionFileNameP))
                    {
                        try
                        {


                            string BoxHead = $"时间,产品ID,线体编号,设备编号,正负极,工位,极卷ID,V角深度纠偏,V角宽度纠偏,白夜班,检测结果,不良类型,NG分类,{PublicSet.Myset.PJPHeadLengthName + PublicSet.Myset.PJPHeadLengthRange.Trim('：')},{PublicSet.Myset.PJPTailLengthName + PublicSet.Myset.PJPTailLengthRange.Trim('：')},{PublicSet.Myset.PJPHeadWidthName + PublicSet.Myset.PJPHeadWidthRange.Trim('：')},{PublicSet.Myset.PJPTailWidthName + PublicSet.Myset.PJPTailWidthRange.Trim('：')},{PublicSet.Myset.PJELeftShoulderName + PublicSet.Myset.PJELeftShoulderRange.Trim('：')},{PublicSet.Myset.PJERightShoulderName + PublicSet.Myset.PJERightShoulderRange.Trim('：')},{PublicSet.Myset.PJEWidthName + PublicSet.Myset.PJEWidthRange.Trim('：')},{PublicSet.Myset.PJEHeightName + PublicSet.Myset.PJEHeightRange.Trim('：')},{PublicSet.Myset.PCeramicHeightName + PublicSet.Myset.PCeramicHeightRange.Trim('：')},极耳余料,极耳打折,{PublicSet.Myset.PJPCoatingName + PublicSet.Myset.PJPCoatingRange.Trim('：')},{PublicSet.Myset.PJPTotalWidthName + PublicSet.Myset.PJPTotalWidthRange.Trim('：')},{PublicSet.Myset.PLeftUpAngleName + PublicSet.Myset.PLeftUpAngleRange.Trim('：')},{PublicSet.Myset.PRightUpAngleName + PublicSet.Myset.PRightUpAngleRange.Trim('：')},{PublicSet.Myset.PLeftDownAngleName + PublicSet.Myset.PLeftDownAngleRange.Trim('：')},{PublicSet.Myset.PRightDownAngleName + PublicSet.Myset.PRightDownAngleRange.Trim('：')},{PublicSet.Myset.PLeftUpBevelName + PublicSet.Myset.PLeftUpBevelRange},{PublicSet.Myset.PRightUpBevelName + PublicSet.Myset.PRightUpBevelRange},{PublicSet.Myset.PLeftDownBevelName + PublicSet.Myset.PLeftDownBevelRange},{PublicSet.Myset.PRightDownBevelName + PublicSet.Myset.PRightDownBevelRange},{PublicSet.Myset.PLeftUpVAngleName + PublicSet.Myset.PLeftUpVAngleRange.Trim('：')},{PublicSet.Myset.PLeftUpVWidthName + PublicSet.Myset.PLeftUpVWidthRange.Trim('：')},{PublicSet.Myset.PLeftUpVDepthName + PublicSet.Myset.PLeftUpVDepthRange.Trim('：')},{PublicSet.Myset.PRightUpVAngleName + PublicSet.Myset.PRightUpVAngleRange.Trim('：')},{PublicSet.Myset.PRightUpVWidthName + PublicSet.Myset.PRightUpVWidthRange},{PublicSet.Myset.PRightUpVDepthName + PublicSet.Myset.PRightUpVDepthRange.Trim('：')},{PublicSet.Myset.PLeftDownVAngleName + PublicSet.Myset.PLeftDownVAngleRange.Trim('：')},{PublicSet.Myset.PLeftDownVWidthName + PublicSet.Myset.PLeftDownVWidthRange},{PublicSet.Myset.PLeftDownVDepthName + PublicSet.Myset.PLeftDownVDepthRange.Trim('：')},{PublicSet.Myset.PRightDownVAngleName + PublicSet.Myset.PRightDownVAngleRange.Trim('：')},{PublicSet.Myset.PRightDownVWidthName + PublicSet.Myset.PRightDownVWidthRange.Trim('：')},{PublicSet.Myset.PRightDownVDepthName.Trim('：')},极片偏移-皮带方向,极片偏移-非皮带方向,极片偏移-角度,左上MarkX,左上MarkY,右上MarkX,右上MarkY,左下MarkX,左下MarkY,右下MarkX,右下MarkY,Time";
                            fs = new FileStream(ProductionFileNameP, FileMode.Create, FileAccess.Write);
                            sw1 = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                            sw1.WriteLine(BoxHead);
                            sw1.Flush();
                            sw1.Close();
                            fs.Close();
                            fs.Dispose();
                            bP = true;
                        }
                        catch (Exception)
                        {

                        }
                    }
                }
                if (bN)
                {
                    try
                    {
                        bN = false;
                        swN = new StreamWriter(ProductionFileNameN, true, Encoding.GetEncoding("gb2312"));
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("负极生产数据表格被占用，无法正常打开，请关闭表格后重启软件！");
                    }
                }
                if (bP)
                {
                    try
                    {
                        bP = false;
                        swP = new StreamWriter(ProductionFileNameP, true, Encoding.GetEncoding("gb2312"));
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("正极生产数据表格被占用，无法正常打开，请关闭表格后重启软件！");
                    }
                }


                #endregion

                #region 片位数据路径
                if (!Directory.Exists(Replace(PublicSet.Myset.PWDataSava, "", "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID)))
                {
                    Directory.CreateDirectory(Replace(PublicSet.Myset.PWDataSava, "", "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID));
                }
                if (!Directory.Exists(Replace(PublicSet.Myset.PWDataSava, "", "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID)))
                {
                    Directory.CreateDirectory(Replace(PublicSet.Myset.PWDataSava, "", "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID));
                }

                PW_NG_BaiPianP = Replace(PublicSet.Myset.PWDataSava, "", "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "\\" + Replace(PublicSet.Myset.PWName, "", "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "NG_百片.csv";

                PW_NG_BaiPianN = Replace(PublicSet.Myset.PWDataSava, "", "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "\\" + Replace(PublicSet.Myset.PWName, "", "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "NG_百片.csv";

                if (!File.Exists(PW_NG_BaiPianP.ToString()) || !File.Exists(PW_NG_BaiPianN.ToString()))
                {
                    string BoxHead = "日期,线体编号,设备编号,正负极,工位,班次,片位是否调整,开始时间,截至时间,极片偏移-皮带方向最大,极片偏移-皮带方向最小,极片偏移-皮带方向平均,极片偏移-皮带方向标准差,极片偏移-非皮带方向最大,极片偏移-非皮带方向最小,极片偏移-非皮带方向平均,极片偏移-非皮带方向标准差,极片偏移-Z最大,极片偏移-Z最小,极片偏移-Z平均,极片偏移-Z标准差";

                    //负极片位数据分析表格百片次
                    if (!File.Exists(PW_NG_BaiPianN.ToString()))
                    {
                        fs = new FileStream(PW_NG_BaiPianN, FileMode.Create, FileAccess.Write);
                        sw1 = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                        sw1.WriteLine(BoxHead);
                        sw1.Flush();
                        sw1.Close();
                        fs.Close();
                        fs.Dispose();
                    }
                    //正极片位数据分析表格百片次
                    if (!File.Exists(PW_NG_BaiPianP.ToString()))
                    {
                        fs = new FileStream(PW_NG_BaiPianP, FileMode.Create, FileAccess.Write);
                        sw1 = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                        sw1.WriteLine(BoxHead);
                        sw1.Flush();
                        sw1.Close();
                        fs.Close();
                        fs.Dispose();
                    }
                }

                #endregion

                #region 统计数据路径
                //生成文件夹
                if (!Directory.Exists(Replace(PublicSet.Myset.TJDataSava, "", "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID)))
                {

                    Directory.CreateDirectory(Replace(PublicSet.Myset.TJDataSava, "", "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID));
                }
                if (!Directory.Exists(Replace(PublicSet.Myset.TJDataSava, "", "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID)))
                {
                    Directory.CreateDirectory(Replace(PublicSet.Myset.TJDataSava, "", "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID));
                }

                //数据路径初始化
                TJ_NG_WeiJuanP = Replace(PublicSet.Myset.TJDataSava, "", "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "\\" + Replace(PublicSet.Myset.TJName, "", "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "NG_尾卷.csv";

                TJ_NG_WeiJuanN = Replace(PublicSet.Myset.TJDataSava, "", "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "\\" + Replace(PublicSet.Myset.TJName, "", "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "NG_尾卷.csv";


                //TJ_NG_WeiJuanN_123 = Replace(PublicSet.Myset.TJDataSava, "", "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "\\" + Replace(PublicSet.Myset.TJName, "", "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "NG_尾卷-123.csv";

                TJ_NG_BanCiN = Replace(PublicSet.Myset.TJDataSava, "", "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "\\" + Replace(PublicSet.Myset.TJName, "", "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "NG_班次.csv";

                TJ_NG_BanCiP = Replace(PublicSet.Myset.TJDataSava, "", "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "\\" + Replace(PublicSet.Myset.TJName, "", "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "NG_班次.csv";

                TJ_NG_BanCiN_Priority = Replace(PublicSet.Myset.TJDataSava, "", "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "\\" + Replace(PublicSet.Myset.TJName, "", "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "_NG_班次优先级.csv";

                TJ_NG_BanCiP_Priority = Replace(PublicSet.Myset.TJDataSava, "", "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "\\" + Replace(PublicSet.Myset.TJName, "", "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "NG_班次优先级.csv";

                //string BoxHead = "日期,线体编号,设备编号,正负极,工位,班次,开始时间,截至时间,极片总数,极片NG数,一档,二档,三档，极片头长,极片尾长,极片头宽,极片尾宽,左肩宽,右肩宽,极耳宽,极耳高,陶瓷高/带料高,极耳打折,涂布高,极片总长,左上垂直度,右上垂直度,左下垂直度,右下垂直度,左上缺角,右上缺角,左下缺角,右下缺角,左上V角度,左上V宽度,左上V深度,右上V角度,右上V宽度,右上V深度,左下V角度,左下V宽度,左下V深度,右下V角度,右下V宽度,右下V深度,找边失败,极片偏移－X最大,极片偏移－X最小,极片偏移－X平均,极片偏移－X标准差,极片偏移－Y最大,极片偏移－Y最小,极片偏移－Y平均,极片偏移－Y标准差,极片偏移－Z最大,极片偏移－Z最小,极片偏移－Z平均,极片偏移－Z标准差";
                string BoxHeadN = $"日期,线体编号,设备编号,正负极,工位,班次,开始时间,截至时间,极片总数,极片NG数,一档,二档,三档,{PublicSet.Myset.NJPHeadLengthName}1-1,{PublicSet.Myset.NJPTailLengthName}1-2,{PublicSet.Myset.NJPHeadWidthName}3-1,{PublicSet.Myset.NJPTailWidthName}3-2,{PublicSet.Myset.NJELeftShoulderName}2-4,{PublicSet.Myset.NJERightShoulderName}2-5,{PublicSet.Myset.NJEWidthName}2-3,{PublicSet.Myset.NJEHeightName}2-2,{PublicSet.Myset.NDLHeightName}1-4,极耳余料1-5,极耳打折2-1,{PublicSet.Myset.NJPCoatingName}1-3,{PublicSet.Myset.NJPTotalWidthName}3-4,{PublicSet.Myset.NLeftUpAngleName}3-3,{PublicSet.Myset.NRightUpAngleName}3-3,{PublicSet.Myset.NLeftDownAngleName}3-3,{PublicSet.Myset.NRightDownAngleName}3-3,{PublicSet.Myset.NLeftUpBevelName}3-3,{PublicSet.Myset.NRightUpBevelName}3-3,{PublicSet.Myset.NLeftDownBevelName}3-3,{PublicSet.Myset.NRightDownBevelName}3-3,{PublicSet.Myset.NLeftUpVAngleName}3-3,{PublicSet.Myset.NLeftUpVWidthName}3-3,{PublicSet.Myset.NLeftUpVDepthName}3-3,{PublicSet.Myset.NRightUpVAngleName}3-3,{PublicSet.Myset.NRightUpVWidthName}3-3,{PublicSet.Myset.NRightUpVDepthName}3-3,{PublicSet.Myset.NLeftDownVAngleName}3-3,{PublicSet.Myset.NLeftDownVWidthName}3-3,{PublicSet.Myset.NLeftDownVDepthName}3-3,{PublicSet.Myset.NRightDownVAngleName}3-3,{PublicSet.Myset.NRightDownVWidthName}3-3,{PublicSet.Myset.NRightDownVDepthName}3-3,找边失败3-5,极片偏移－X最大,极片偏移－X最小,极片偏移－X平均,极片偏移－X标准差,极片偏移－Y最大,极片偏移－Y最小,极片偏移－Y平均,极片偏移－Y标准差,极片偏移－Z最大,极片偏移－Z最小,极片偏移－Z平均,极片偏移－Z标准差";

                string BoxHeadP = $"日期,线体编号,设备编号,正负极,工位,班次,开始时间,截至时间,极片总数,极片NG数,一档,二档,三档,{PublicSet.Myset.PJPHeadLengthName}1-1,{PublicSet.Myset.PJPTailLengthName}1-2,{PublicSet.Myset.PJPHeadWidthName}3-1,{PublicSet.Myset.PJPTailWidthName}3-2,{PublicSet.Myset.PJELeftShoulderName}2-4,{PublicSet.Myset.PJERightShoulderName}2-5,{PublicSet.Myset.PJEWidthName}2-3,{PublicSet.Myset.PJEHeightName}2-2,{PublicSet.Myset.PCeramicHeightName}1-4,极耳余料1-5,极耳打折2-1,{PublicSet.Myset.PJPCoatingName}1-3,{PublicSet.Myset.PJPTotalWidthName}3-4,{PublicSet.Myset.PLeftUpAngleName}3-3,{PublicSet.Myset.PRightUpAngleName}3-3,{PublicSet.Myset.PLeftDownAngleName}3-3,{PublicSet.Myset.PRightDownAngleName}3-3,{PublicSet.Myset.PLeftUpBevelName}3-3,{PublicSet.Myset.PRightUpBevelName}3-3,{PublicSet.Myset.PLeftDownBevelName}3-3,{PublicSet.Myset.PRightDownBevelName}3-3,{PublicSet.Myset.PLeftUpVAngleName}3-3,{PublicSet.Myset.PLeftUpVWidthName}3-3,{PublicSet.Myset.PLeftUpVDepthName}3-3,{PublicSet.Myset.PRightUpVAngleName}3-3,{PublicSet.Myset.PRightUpVWidthName}3-3,{PublicSet.Myset.PRightUpVDepthName}3-3,{PublicSet.Myset.PLeftDownVAngleName}3-3,{PublicSet.Myset.PLeftDownVWidthName}3-3,{PublicSet.Myset.PLeftDownVDepthName}3-3,{PublicSet.Myset.PRightDownVAngleName}3-3,{PublicSet.Myset.PRightDownVWidthName}3-3,{PublicSet.Myset.PRightDownVDepthName}3-3,找边失败3-5,极片偏移－X最大,极片偏移－X最小,极片偏移－X平均,极片偏移－X标准差,极片偏移－Y最大,极片偏移－Y最小,极片偏移－Y平均,极片偏移－Y标准差,极片偏移－Z最大,极片偏移－Z最小,极片偏移－Z平均,极片偏移－Z标准差";


                #region 按班次生成
                if (!File.Exists(TJ_NG_BanCiN.ToString()) || !File.Exists(TJ_NG_BanCiP.ToString()))
                {
                    //NG分析表格每班次－负极
                    if (!File.Exists(TJ_NG_BanCiN.ToString()))
                    {
                        fs = new FileStream(TJ_NG_BanCiN, FileMode.Create, FileAccess.Write);
                        sw1 = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                        sw1.WriteLine(BoxHeadN);
                        sw1.Flush();
                        sw1.Close();
                        fs.Close();
                        fs.Dispose();
                    }
                    //NG分析表格每班次－正极
                    if (!File.Exists(TJ_NG_BanCiP.ToString()))
                    {
                        fs = new FileStream(TJ_NG_BanCiP, FileMode.Create, FileAccess.Write);
                        sw1 = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                        sw1.WriteLine(BoxHeadP);
                        sw1.Flush();
                        sw1.Close();
                        fs.Close();
                        fs.Dispose();
                    }

                }
                #endregion
                #region 按尾卷生成

                string BoxHeadN_J = $"日期,线体编号,设备编号,正负极,工位,极卷ID,初始卷径,开始时间,截至时间,极片总数,极片NG数,一档,二档,三档,{PublicSet.Myset.NJPHeadLengthName}1-1,{PublicSet.Myset.NJPTailLengthName}1-2,{PublicSet.Myset.NJPHeadWidthName}3-1,{PublicSet.Myset.NJPTailWidthName}3-2,{PublicSet.Myset.NJELeftShoulderName}2-4,{PublicSet.Myset.NJERightShoulderName}2-5,{PublicSet.Myset.NJEWidthName}2-3,{PublicSet.Myset.NJEHeightName}2-2,{PublicSet.Myset.NDLHeightName}1-4,极耳余料1-5,极耳打折2-1,{PublicSet.Myset.NJPCoatingName}1-3,{PublicSet.Myset.NJPTotalWidthName}3-4,{PublicSet.Myset.NLeftUpAngleName}3-3,{PublicSet.Myset.NRightUpAngleName}3-3,{PublicSet.Myset.NLeftDownAngleName}3-3,{PublicSet.Myset.NRightDownAngleName}3-3,{PublicSet.Myset.NLeftUpBevelName}3-3,{PublicSet.Myset.NRightUpBevelName}3-3,{PublicSet.Myset.NLeftDownBevelName}3-3,{PublicSet.Myset.NRightDownBevelName}3-3,{PublicSet.Myset.NLeftUpVAngleName}3-3,{PublicSet.Myset.NLeftUpVWidthName}3-3,{PublicSet.Myset.NLeftUpVDepthName}3-3,{PublicSet.Myset.NRightUpVAngleName}3-3,{PublicSet.Myset.NRightUpVWidthName}3-3,{PublicSet.Myset.NRightUpVDepthName}3-3,{PublicSet.Myset.NLeftDownVAngleName}3-3,{PublicSet.Myset.NLeftDownVWidthName}3-3,{PublicSet.Myset.NLeftDownVDepthName}3-3,{PublicSet.Myset.NRightDownVAngleName}3-3,{PublicSet.Myset.NRightDownVWidthName}3-3,{PublicSet.Myset.NRightDownVDepthName}3-3,找边失败3-5,极片偏移－X最大,极片偏移－X最小,极片偏移－X平均,极片偏移－X标准差,极片偏移－Y最大,极片偏移－Y最小,极片偏移－Y平均,极片偏移－Y标准差,极片偏移－Z最大,极片偏移－Z最小,极片偏移－Z平均,极片偏移－Z标准差";

                string BoxHeadP_J = $"日期,线体编号,设备编号,正负极,工位,极卷ID,初始卷径,开始时间,截至时间,极片总数,极片NG数,一档,二档,三档,{PublicSet.Myset.PJPHeadLengthName}1-1,{PublicSet.Myset.PJPTailLengthName}1-2,{PublicSet.Myset.PJPHeadWidthName}3-1,{PublicSet.Myset.PJPTailWidthName}3-2,{PublicSet.Myset.PJELeftShoulderName}2-4,{PublicSet.Myset.PJERightShoulderName}2-5,{PublicSet.Myset.PJEWidthName}2-3,{PublicSet.Myset.PJEHeightName}2-2,{PublicSet.Myset.PCeramicHeightName}1-4,极耳余料1-5,极耳打折2-1,{PublicSet.Myset.PJPCoatingName}1-3,{PublicSet.Myset.PJPTotalWidthName}3-4,{PublicSet.Myset.PLeftUpAngleName}3-3,{PublicSet.Myset.PRightUpAngleName}3-3,{PublicSet.Myset.PLeftDownAngleName}3-3,{PublicSet.Myset.PRightDownAngleName}3-3,{PublicSet.Myset.PLeftUpBevelName}3-3,{PublicSet.Myset.PRightUpBevelName}3-3,{PublicSet.Myset.PLeftDownBevelName}3-3,{PublicSet.Myset.PRightDownBevelName}3-3,{PublicSet.Myset.PLeftUpVAngleName}3-3,{PublicSet.Myset.PLeftUpVWidthName}3-3,{PublicSet.Myset.PLeftUpVDepthName}3-3,{PublicSet.Myset.PRightUpVAngleName}3-3,{PublicSet.Myset.PRightUpVWidthName}3-3,{PublicSet.Myset.PRightUpVDepthName}3-3,{PublicSet.Myset.PLeftDownVAngleName}3-3,{PublicSet.Myset.PLeftDownVWidthName}3-3,{PublicSet.Myset.PLeftDownVDepthName}3-3,{PublicSet.Myset.PRightDownVAngleName}3-3,{PublicSet.Myset.PRightDownVWidthName}3-3,{PublicSet.Myset.PRightDownVDepthName}3-3,找边失败3-5,极片偏移－X最大,极片偏移－X最小,极片偏移－X平均,极片偏移－X标准差,极片偏移－Y最大,极片偏移－Y最小,极片偏移－Y平均,极片偏移－Y标准差,极片偏移－Z最大,极片偏移－Z最小,极片偏移－Z平均,极片偏移－Z标准差";


                //NG分析表格每尾卷－负极
                if (!File.Exists(TJ_NG_WeiJuanN.ToString()))
                {
                    fs = new FileStream(TJ_NG_WeiJuanN, FileMode.Create, FileAccess.Write);
                    sw1 = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                    sw1.WriteLine(BoxHeadN_J);
                    sw1.Flush();
                    sw1.Close();
                    fs.Close();
                    fs.Dispose();
                }




                //NG分析表格每尾卷－正极
                if (!File.Exists(TJ_NG_WeiJuanP.ToString()))
                {
                    fs = new FileStream(TJ_NG_WeiJuanP, FileMode.Create, FileAccess.Write);
                    sw1 = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                    sw1.WriteLine(BoxHeadP_J);
                    sw1.Flush();
                    sw1.Close();
                    fs.Close();
                    fs.Dispose();
                }


                #endregion
                #region 班次优先级              
                //NG分析表格每班次优先级－负极
                if (!File.Exists(TJ_NG_BanCiN_Priority.ToString()))
                {
                    fs = new FileStream(TJ_NG_BanCiN_Priority, FileMode.Create, FileAccess.Write);
                    sw1 = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                    sw1.WriteLine(BoxHeadN);
                    sw1.Flush();
                    sw1.Close();
                    fs.Close();
                    fs.Dispose();
                }
                //NG分析表格每班次优先级－正极
                if (!File.Exists(TJ_NG_BanCiP_Priority.ToString()))
                {
                    fs = new FileStream(TJ_NG_BanCiP_Priority, FileMode.Create, FileAccess.Write);
                    sw1 = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                    sw1.WriteLine(BoxHeadP);
                    sw1.Flush();
                    sw1.Close();
                    fs.Close();
                    fs.Dispose();
                }

                #endregion

                #endregion

                PublicSet.Myset.WorkingShift = MornOrNight;
                return true;
            }
            catch (Exception ex)
            {
                LogForm("生成数据表头错误" + ex.ToString());
                return false;
            }
        }

        /// <summary>
        /// 创建MES数据表头-创建MES图文件夹
        /// </summary>
        public static void CreateCSV_MES()
        {
            if (PublicSet.Myset.MESPictureSwitch)
            {
                string filepath = Tool.Replace(PublicSet.Myset.PathMES, PublicSet.Myset.WorkingShift, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN);
                if (!Directory.Exists(filepath))
                {
                    Directory.CreateDirectory(filepath);
                }
                filepath = Tool.Replace(PublicSet.Myset.PathMES, PublicSet.Myset.WorkingShift, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP);
                if (!Directory.Exists(filepath))
                {
                    Directory.CreateDirectory(filepath);
                }
            }
            if (!PublicSet.Myset.MESDataSwitch) return;
            #region MES数据路径  
            string MornOrNight = "";
            int MorningResult = DateTime.Compare(DateTime.Now, Convert.ToDateTime(PublicSet.Myset.Morn));
            int NightResult = DateTime.Compare(DateTime.Now, Convert.ToDateTime(PublicSet.Myset.Night));

            if (PublicSet.Myset.MESDataSava.Contains("WS"))//判断是否存在按班次生成
            {
                if (MorningResult == -1 && NightResult == -1)//凌晨时间为前一天夜班
                {
                    MornOrNight = "晚班";
                    MESFileNameN = Replace_Yesterday(PublicSet.Myset.MESDataSava, MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN) + "\\" + Replace_Yesterday(PublicSet.Myset.SCName, MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN) + ".csv";

                    MESFileNameP = Replace_Yesterday(PublicSet.Myset.MESDataSava, MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP) + "\\" + Replace_Yesterday(PublicSet.Myset.SCName, MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP) + ".csv";

                    //判断是否存在表格，不存在则生成
                    if (!Directory.Exists(Replace_Yesterday(PublicSet.Myset.MESDataSava, MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP)))
                    {
                        Directory.CreateDirectory(Replace_Yesterday(PublicSet.Myset.MESDataSava, MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP));
                    }
                    //判断是否存在表格，不存在则生成
                    if (!Directory.Exists(Replace_Yesterday(PublicSet.Myset.MESDataSava, MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN)))
                    {
                        Directory.CreateDirectory(Replace_Yesterday(PublicSet.Myset.MESDataSava, MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN));
                    }
                }
                if (MorningResult == 1 && NightResult == 1 || NightResult == 0)//当天夜班并非凌晨
                {
                    MornOrNight = "晚班";
                    MESFileNameN = Replace(PublicSet.Myset.MESDataSava, MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN) + "\\" + Replace(PublicSet.Myset.SCName, "晚班", "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN) + ".csv";

                    MESFileNameP = Replace(PublicSet.Myset.MESDataSava, MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP) + "\\" + Replace(PublicSet.Myset.SCName, "晚班", "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP) + ".csv";

                    if (!Directory.Exists(Replace(PublicSet.Myset.MESDataSava, MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP)))
                    {
                        Directory.CreateDirectory(Replace(PublicSet.Myset.MESDataSava, MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP));
                    }
                    if (!Directory.Exists(Replace(PublicSet.Myset.MESDataSava, MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN)))
                    {
                        Directory.CreateDirectory(Replace(PublicSet.Myset.MESDataSava, MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN));
                    }
                }
                if ((MorningResult == 1 && NightResult == -1) || MorningResult == 0)//当天白班
                {
                    MornOrNight = "白班";
                    MESFileNameN = Replace(PublicSet.Myset.MESDataSava, MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN) + "\\" + Replace(PublicSet.Myset.SCName, "白班", "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN) + ".csv";

                    MESFileNameP = Replace(PublicSet.Myset.MESDataSava, MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP) + "\\" + Replace(PublicSet.Myset.SCName, "白班", "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP) + ".csv";

                    if (!Directory.Exists(Replace(PublicSet.Myset.MESDataSava, MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP)))
                    {
                        Directory.CreateDirectory(Replace(PublicSet.Myset.MESDataSava, MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP));
                    }
                    if (!Directory.Exists(Replace(PublicSet.Myset.MESDataSava, MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN)))
                    {
                        Directory.CreateDirectory(Replace(PublicSet.Myset.MESDataSava, MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN));
                    }
                }
            }
            else
            {

                MESFileNameN = Replace(PublicSet.Myset.MESDataSava, MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN) + "\\" + Replace(PublicSet.Myset.MESName, "", "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN) + ".csv";

                MESFileNameP = Replace(PublicSet.Myset.MESDataSava, MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP) + "\\" + Replace(PublicSet.Myset.MESName, "", "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP) + ".csv";

                if (!Directory.Exists(Replace(PublicSet.Myset.MESDataSava, MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP)))
                {
                    Directory.CreateDirectory(Replace(PublicSet.Myset.MESDataSava, MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDP));
                }
                if (!Directory.Exists(Replace(PublicSet.Myset.MESDataSava, MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN)))
                {
                    Directory.CreateDirectory(Replace(PublicSet.Myset.MESDataSava, MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID, PublicSet.PolePieceIDN));
                }
            }

            FileStream fs; StreamWriter sw1;
            //负极白夜班MES数据
            if (!File.Exists(MESFileNameN))
            {
                string BoxHead = $"时间,产品ID,线体编号,设备编号,正负极,工位,极卷ID,V角深度纠偏,V角宽度纠偏,白夜班,检测结果,不良类型,{PublicSet.Myset.NJPHeadLengthName},{PublicSet.Myset.NJPTailLengthName},{PublicSet.Myset.NJPHeadWidthName},{PublicSet.Myset.NJPTailWidthName},{PublicSet.Myset.NJELeftShoulderName},{PublicSet.Myset.NJERightShoulderName},{PublicSet.Myset.NJEWidthName},{PublicSet.Myset.NJEHeightName},{PublicSet.Myset.NDLHeightName},极耳余料,极耳打折,{PublicSet.Myset.NJPCoatingName},{PublicSet.Myset.NJPTotalWidthName},{PublicSet.Myset.NLeftUpAngleName},{PublicSet.Myset.NRightUpAngleName},{PublicSet.Myset.NLeftDownAngleName},{PublicSet.Myset.NRightDownAngleName},{PublicSet.Myset.NLeftUpBevelName},{PublicSet.Myset.NRightUpBevelName},{PublicSet.Myset.NLeftDownBevelName},{PublicSet.Myset.NRightDownBevelName},{PublicSet.Myset.NLeftUpVAngleName},{PublicSet.Myset.NLeftUpVWidthName},{PublicSet.Myset.NLeftUpVDepthName},{PublicSet.Myset.NRightUpVAngleName},{PublicSet.Myset.NRightUpVWidthName},{PublicSet.Myset.NRightUpVDepthName},{PublicSet.Myset.NLeftDownVAngleName},{PublicSet.Myset.NLeftDownVWidthName},{PublicSet.Myset.NLeftDownVDepthName},{PublicSet.Myset.NRightDownVAngleName},{PublicSet.Myset.NRightDownVWidthName},{PublicSet.Myset.NRightDownVDepthName},极片偏移-皮带方向,极片偏移-非皮带方向,极片偏移-角度";
                fs = new FileStream(MESFileNameN, FileMode.Create, FileAccess.Write);
                sw1 = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                sw1.WriteLine(BoxHead);
                sw1.Flush();
                sw1.Close();
                fs.Close();
                fs.Dispose();
                //bN = true;
            }

            //正极白夜班MES数据
            if (!File.Exists(MESFileNameP))
            {
                string BoxHead = $"时间,产品ID,线体编号,设备编号,正负极,工位,极卷ID,V角深度纠偏,V角宽度纠偏,白夜班,检测结果,不良类型,{PublicSet.Myset.PJPHeadLengthName},{PublicSet.Myset.PJPTailLengthName},{PublicSet.Myset.PJPHeadWidthName},{PublicSet.Myset.PJPTailWidthName},{PublicSet.Myset.PJELeftShoulderName},{PublicSet.Myset.PJERightShoulderName},{PublicSet.Myset.PJEWidthName},{PublicSet.Myset.PJEHeightName},{PublicSet.Myset.PCeramicHeightName},极耳余料,极耳打折,{PublicSet.Myset.PJPCoatingName},{PublicSet.Myset.PJPTotalWidthName},{PublicSet.Myset.PLeftUpAngleName},{PublicSet.Myset.PRightUpAngleName},{PublicSet.Myset.PLeftDownAngleName},{PublicSet.Myset.PRightDownAngleName},{PublicSet.Myset.PLeftUpBevelName},{PublicSet.Myset.PRightUpBevelName},{PublicSet.Myset.PLeftDownBevelName},{PublicSet.Myset.PRightDownBevelName},{PublicSet.Myset.PLeftUpVAngleName},{PublicSet.Myset.PLeftUpVWidthName},{PublicSet.Myset.PLeftUpVDepthName},{PublicSet.Myset.PRightUpVAngleName},{PublicSet.Myset.PRightUpVWidthName},{PublicSet.Myset.PRightUpVDepthName},{PublicSet.Myset.PLeftDownVAngleName},{PublicSet.Myset.PLeftDownVWidthName},{PublicSet.Myset.PLeftDownVDepthName},{PublicSet.Myset.PRightDownVAngleName},{PublicSet.Myset.PRightDownVWidthName},{PublicSet.Myset.PRightDownVDepthName},极片偏移-皮带方向,极片偏移-非皮带方向,极片偏移-角度";
                fs = new FileStream(MESFileNameP, FileMode.Create, FileAccess.Write);
                sw1 = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                sw1.WriteLine(BoxHead);
                sw1.Flush();
                sw1.Close();
                fs.Close();
                fs.Dispose();
                //bP = true;
            }

            //if (bN)
            //{
            //    try
            //    {
            //        bN = false;
            //        swN = new StreamWriter(ProductionFileNameN, true, Encoding.GetEncoding("gb2312"));
            //    }
            //    catch (Exception ex)
            //    {
            //        System.Windows.MessageBox.Show("负极生产数据表格被占用，无法正常打开，请关闭表格后重启软件！");
            //    }
            //}
            //if (bP)
            //{
            //    try
            //    {
            //        bP = false;
            //swP = new StreamWriter(ProductionFileNameP, true, Encoding.GetEncoding("gb2312"));
            //    }
            //    catch (Exception)
            //    {

            //        System.Windows.MessageBox.Show("正极生产数据表格被占用，无法正常打开，请关闭表格后重启软件！");
            //    }
            //}

            #endregion
        }

        /// <summary>
        /// 生产数据-csv表格
        /// </summary>
        /// <param name="data"></param>
        /// <param name="bs">V角深度纠偏是否开启</param>
        /// <param name="bk">V角宽度纠偏是否开启</param>
        /// <param name="ImageTime">检测耗时</param>
        public static void WriteDataCsv(Data data, string PolePieceid, bool bDepth, bool bWidth)
        {
            //   BoxHead = "时间,产品ID,线体编号,设备编号,工位,极卷ID,V角深度纠偏,V角宽度纠偏,正负极,白夜班,检测结果,不良类型,极片头长,极片尾长,极片头宽,极片尾宽,左肩宽,右肩宽,极耳宽,极耳高,陶瓷高/带料高,极耳余料，极耳打折,涂布高,极片总长,左上垂直度,右上垂直度,左下垂直度,右下垂直度,左上缺角面积,右上缺角面积,左下缺角面积,右下缺角面积,左上V角度,左上V宽度,左上V深度,右上V角度,右上V宽度,右上V深度,左下V角度,左下V宽度,左下V深度,右下V角度,右下V宽度,右下V深度,极片偏移-皮带方向,极片偏移-非皮带方向,极片偏移-角度";
            try
            {
                string str = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")},{data.ProductID},{PublicSet.Cameraset.LineID},{PublicSet.Cameraset.MachineID},{data.JPType},尺寸,{PolePieceid},{bDepth},{bWidth},{data.WorkingShift},{data.Ruselt},{data.NGType},{data.NGClassify},{data.JPHeadLength},{data.JPTailLength},{data.JPHeadWidth},{data.JPTailWidth},{data.JELeftShoulder},{data.JERightShoulder},{data.JEWidth},{data.JEHeight},{data.DLHeightOrCeramicsHeight},{data.bJeOddments},{data.bJeBevelLimit},{data.JPCoating},{data.JPTotalWidth},{data.LeftUpAngle},{data.RightUpAngle},{data.LeftDownAngle},{data.RightDownAngle},{data.LeftUpBevelArea},{data.RightUpBevelArea},{data.LeftDownBevelArea},{data.RightDownBevelArea},{data.LeftUpVAngle},{data.LeftUpVWidth},{data.LeftUpVDepth},{data.RightUpVAngle},{data.RightUpVWidth},{data.RightUpVDepth},{data.LeftDownVAngle},{data.LeftDownVWidth},{data.LeftDownVDepth},{data.RightDownVAngle},{data.RightDownVWidth},{data.RightDownVDepth},{data.X},{data.Y},{data.Z},{data.LeftUpMarkX},{data.LeftUpMarkY},{data.RightUpMarkX},{data.RightUpMarkY},{data.LeftDownMarkX},{data.LeftDownMarkY},{data.RightDownMarkX},{data.RightDownMarkY},{data.time}";

                if (data.JPType == "负极")
                {
                    swN.WriteLine(str);
                    swN.Flush();
                }
                else
                {
                    swP.WriteLine(str);
                    swP.Flush();
                }
            }
            catch (Exception ex)
            {
                Tool.LogForm("生产数据写入失败！" + ex.ToString());
            }

        }


        /// <summary>
        /// MES数据-csv表格
        /// </summary>
        /// <param name="data"></param>
        /// <param name="bs">V角深度纠偏是否开启</param>
        /// <param name="bk">V角宽度纠偏是否开启</param>
        /// <param name="ImageTime">检测耗时</param>
        public static void WriteDataCsv_MES(Data data, string PolePieceid, bool bDepth, bool bWidth)
        {
            //   BoxHead = "时间,产品ID,线体编号,设备编号,工位,极卷ID,V角深度纠偏,V角宽度纠偏,正负极,白夜班,检测结果,不良类型,极片头长,极片尾长,极片头宽,极片尾宽,左肩宽,右肩宽,极耳宽,极耳高,陶瓷高/带料高,极耳余料，极耳打折,涂布高,极片总长,左上垂直度,右上垂直度,左下垂直度,右下垂直度,左上缺角面积,右上缺角面积,左下缺角面积,右下缺角面积,左上V角度,左上V宽度,左上V深度,右上V角度,右上V宽度,右上V深度,左下V角度,左下V宽度,左下V深度,右下V角度,右下V宽度,右下V深度,极片偏移-皮带方向,极片偏移-非皮带方向,极片偏移-角度";
            try
            {
                string str = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")},{data.ProductID},{PublicSet.Cameraset.LineID},{PublicSet.Cameraset.MachineID},{data.JPType},尺寸,{PolePieceid},{bDepth},{bWidth},{data.WorkingShift},{data.Ruselt},{data.NGType},{data.JPHeadLength},{data.JPTailLength},{data.JPHeadWidth},{data.JPTailWidth},{data.JELeftShoulder},{data.JERightShoulder},{data.JEWidth},{data.JEHeight},{data.DLHeightOrCeramicsHeight},{data.bJeOddments},{data.bJeBevelLimit},{data.JPCoating},{data.JPTotalWidth},{data.LeftUpAngle},{data.RightUpAngle},{data.LeftDownAngle},{data.RightDownAngle},{data.LeftUpBevelArea},{data.RightUpBevelArea},{data.LeftDownBevelArea},{data.RightDownBevelArea},{data.LeftUpVAngle},{data.LeftUpVWidth},{data.LeftUpVDepth},{data.RightUpVAngle},{data.RightUpVWidth},{data.RightUpVDepth},{data.LeftDownVAngle},{data.LeftDownVWidth},{data.LeftDownVDepth},{data.RightDownVAngle},{data.RightDownVWidth},{data.RightDownVDepth},{data.X},{data.Y},{data.Z}";
                if (data.JPType == "负极")
                {
                    //  FileStream fs = new FileStream(MESFileNameN, FileMode.Append, FileAccess.Write);
                    StreamWriter sw = new StreamWriter(MESFileNameN, true, Encoding.GetEncoding("gb2312"));
                    sw.WriteLine(str);
                    sw.Flush();
                    sw.Close();
                }
                else
                {
                    StreamWriter sw = new StreamWriter(MESFileNameP, true, Encoding.GetEncoding("gb2312"));
                    sw.WriteLine(str);
                    sw.Flush();
                    sw.Close();
                }
            }
            catch (Exception ex)
            {
                Tool.LogForm("写入MES数据失败！" + ex.ToString());
            }
        }

        /// <summary>
        /// 写CSV统计数据NG每班次
        /// </summary>
        /// <param name="str"></param>
        /// <param name="Od"></param>
        public static void WriteCsv_TJ_NG_BanCi(string str, JPOffsetData Od)
        {

            try
            {
                //表头BoxHead ="日期,线体编号,设备编号,正负极,班次,开始时间,截至时间,极片总数,极片NG数,一档,二档,三档，极片头长,极片尾长,极片头宽,极片尾宽,左肩宽,右肩宽,极耳宽,极耳高,陶瓷高/带料高,极耳打折,涂布高,极片总长,左上垂直度,右上垂直度,左下垂直度,右下垂直度,左上缺角,右上缺角,左下缺角,右下缺角,左上V角度,左上V宽度,左上V深度,右上V角度,右上V宽度,右上V深度,左下V角度,左下V宽度,左下V深度,右下V角度,右下V宽度,右下V深度,找边失败，极片偏移－X最大,极片偏移－X最小,极片偏移－X平均,极片偏移－X标准差,极片偏移－Y最大,极片偏移－Y最小,极片偏移－Y平均,极片偏移－Y标准差,极片偏移－Z最大,极片偏移－Z最小,极片偏移－Z平均,极片偏移－Z标准差";
                string data;
                if (str.Contains("负极"))
                {
                    data = $"{str},{PublicSet.Datashow.NSum},{PublicSet.Datashow.NSumNG_W},{PublicSet.Datashow.NNGOne},{PublicSet.Datashow.NNGTwo},{PublicSet.Datashow.NNGThree},{PublicSet.Datashow.NJPHeadLengthNGCount},{PublicSet.Datashow.NJPTailLengthNGCount},{PublicSet.Datashow.NJPHeadWidthNGCount},{PublicSet.Datashow.NJPTailWidthNGCount},{PublicSet.Datashow.NJELeftShoulderNGCount},{PublicSet.Datashow.NJERightShoulderNGCount},{PublicSet.Datashow.NJEWidthNGCount},{PublicSet.Datashow.NJEHeightNGCount},{PublicSet.Datashow.NDLHeightNGCount},{PublicSet.Datashow.NJeOddmentsNGCount},{PublicSet.Datashow.NJeBevelLimitNGCount},{PublicSet.Datashow.NJPCoatingNGCount},{PublicSet.Datashow.NJPTotalWidthNGCount},{PublicSet.Datashow.NLeftUpAngleNGCount},{PublicSet.Datashow.NRightUpAngleNGCount},{PublicSet.Datashow.NLeftDownAngleNGCount},{PublicSet.Datashow.NRightDownAngleNGCount},{PublicSet.Datashow.NLeftUpBevelNGCount},{PublicSet.Datashow.NRightUpBevelNGCount},{PublicSet.Datashow.NLeftDownBevelNGCount},{PublicSet.Datashow.NRightDownBevelNGCount},{PublicSet.Datashow.NLeftUpVAngleNGCount},{PublicSet.Datashow.NLeftUpVWidthNGCount},{PublicSet.Datashow.NLeftUpVDepthNGCount},{PublicSet.Datashow.NRightUpVAngleNGCount},{PublicSet.Datashow.NRightUpVWidthNGCount},{PublicSet.Datashow.NRightUpVDepthNGCount},{PublicSet.Datashow.NLeftDownVAngleNGCount},{PublicSet.Datashow.NLeftDownVWidthNGCount},{PublicSet.Datashow.NLeftDownVDepthNGCount},{PublicSet.Datashow.NRightDownVAngleNGCount},{PublicSet.Datashow.NRightDownVWidthNGCount},{PublicSet.Datashow.NRightDownVDepthNGCount},{PublicSet.Datashow.NMeasureLineNGCount},{Od.XMax},{Od.XMin},{Od.XAvg.ToString("0.000")},{Od.XSta.ToString("0.000")},{Od.YMax},{Od.YMin},{Od.YAvg.ToString("0.000")},{Od.YSta.ToString("0.000")},{Od.ZMax},{Od.ZMin},{Od.ZAvg.ToString("0.000")},{Od.ZSta.ToString("0.000")}";
                    FileStream fs = new FileStream(TJ_NG_BanCiN, FileMode.Append, FileAccess.Write);
                    sw = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                    sw.WriteLine(data);
                    fs.Flush(); sw.Close(); fs.Close();
                }
                else
                {
                    data = $"{str},{PublicSet.Datashow.PSum},{PublicSet.Datashow.PSumNG_W},{PublicSet.Datashow.PNGOne},{PublicSet.Datashow.PNGTwo},{PublicSet.Datashow.PNGThree},{PublicSet.Datashow.PJPHeadLengthNGCount},{PublicSet.Datashow.PJPTailLengthNGCount},{PublicSet.Datashow.PJPHeadWidthNGCount},{PublicSet.Datashow.PJPTailWidthNGCount},{PublicSet.Datashow.PJELeftShoulderNGCount},{PublicSet.Datashow.PJERightShoulderNGCount},{PublicSet.Datashow.PJEWidthNGCount},{PublicSet.Datashow.PJEHeightNGCount},{PublicSet.Datashow.PCeramicsHeightNGCount},{PublicSet.Datashow.PJeOddmentsNGCount},{PublicSet.Datashow.PJeBevelLimitNGCount},{PublicSet.Datashow.PJPCoatingNGCount},{PublicSet.Datashow.PJPTotalWidthNGCount},{PublicSet.Datashow.PLeftUpAngleNGCount},{PublicSet.Datashow.PRightUpAngleNGCount},{PublicSet.Datashow.PLeftDownAngleNGCount},{PublicSet.Datashow.PRightDownAngleNGCount},{PublicSet.Datashow.PLeftUpBevelNGCount},{PublicSet.Datashow.PRightUpBevelNGCount},{PublicSet.Datashow.PLeftDownBevelNGCount},{PublicSet.Datashow.PRightDownBevelNGCount},{PublicSet.Datashow.PLeftUpVAngleNGCount},{PublicSet.Datashow.PLeftUpVWidthNGCount},{PublicSet.Datashow.PLeftUpVDepthNGCount},{PublicSet.Datashow.PRightUpVAngleNGCount},{PublicSet.Datashow.PRightUpVWidthNGCount},{PublicSet.Datashow.PRightUpVDepthNGCount},{PublicSet.Datashow.PLeftDownVAngleNGCount},{PublicSet.Datashow.PLeftDownVWidthNGCount},{PublicSet.Datashow.PLeftDownVDepthNGCount},{PublicSet.Datashow.PRightDownVAngleNGCount},{PublicSet.Datashow.PRightDownVWidthNGCount},{PublicSet.Datashow.PRightDownVDepthNGCount},{PublicSet.Datashow.PMeasureLineNGCount},{Od.XMax},{Od.XMin},{Od.XAvg.ToString("0.000")},{Od.XSta.ToString("0.000")},{Od.YMax},{Od.YMin},{Od.YAvg.ToString("0.000")},{Od.YSta.ToString("0.000")},{Od.ZMax},{Od.ZMin},{Od.ZAvg.ToString("0.000")},{Od.ZSta.ToString("0.000")}";
                    FileStream fs = new FileStream(TJ_NG_BanCiP, FileMode.Append, FileAccess.Write);
                    StreamWriter sw = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                    sw.WriteLine(data);
                    fs.Flush();
                    sw.Close(); fs.Close();
                }
            }
            catch (Exception ex)
            {
                Tool.LogForm("表格被占用" + ex.ToString());
            }

        }

        /// <summary>
        /// 写CSV统计数据NG每极卷
        /// </summary>
        /// <param name="str"></param>
        /// <param name="Od"></param>
        public static void WriteCsv_TJ_NG_WeiJuan(string str)
        {
            //表头BoxHead ="日期,线体编号,设备编号,正负极,班次,开始时间,截至时间,极片总数,极片NG数,极片头长,极片尾长,极片头宽,极片尾宽,左肩宽,右肩宽,极耳宽,极耳高,陶瓷高/带料高,极耳余料，极耳打折,涂布高,极片总长,左上垂直度,右上垂直度,左下垂直度,右下垂直度,左上缺角,右上缺角,左下缺角,右下缺角,左上V角度,左上V宽度,左上V深度,右上V角度,右上V宽度,右上V深度,左下V角度,左下V宽度,左下V深度,右下V角度,右下V宽度,右下V深度,找边失败，极片偏移－X最大,极片偏移－X最小,极片偏移－X平均,极片偏移－X标准差,极片偏移－Y最大,极片偏移－Y最小,极片偏移－Y平均,极片偏移－Y标准差,极片偏移－Z最大,极片偏移－Z最小,极片偏移－Z平均,极片偏移－Z标准差";
            string data;
            if (str.Contains("负极"))
            {
                data = $"{str},{PublicSet.Datashow.NSum_J},{PublicSet.Datashow.NSumNG_J},{PublicSet.Datashow.NNGOne_J},{PublicSet.Datashow.NNGTwo_J},{PublicSet.Datashow.NNGThree_J},{PublicSet.Datashow.NJPHeadLengthNGCount_J},{PublicSet.Datashow.NJPTailLengthNGCount_J},{PublicSet.Datashow.NJPHeadWidthNGCount_J},{PublicSet.Datashow.NJPTailWidthNGCount_J},{PublicSet.Datashow.NJELeftShoulderNGCount_J},{PublicSet.Datashow.NJERightShoulderNGCount_J},{PublicSet.Datashow.NJEWidthNGCount_J},{PublicSet.Datashow.NJEHeightNGCount_J},{PublicSet.Datashow.NDLHeightNGCount_J},{PublicSet.Datashow.NJeOddmentsNGCount_J},{PublicSet.Datashow.NJeBevelLimitNGCount_J},{PublicSet.Datashow.NJPCoatingNGCount_J},{PublicSet.Datashow.NJPTotalWidthNGCount_J},{PublicSet.Datashow.NLeftUpAngleNGCount_J},{PublicSet.Datashow.NRightUpAngleNGCount_J},{PublicSet.Datashow.NLeftDownAngleNGCount_J},{PublicSet.Datashow.NRightDownAngleNGCount_J},{PublicSet.Datashow.NLeftUpBevelNGCount_J},{PublicSet.Datashow.NRightUpBevelNGCount_J},{PublicSet.Datashow.NLeftDownBevelNGCount_J},{PublicSet.Datashow.NRightDownBevelNGCount_J},{PublicSet.Datashow.NLeftUpVAngleNGCount_J},{PublicSet.Datashow.NLeftUpVWidthNGCount_J},{PublicSet.Datashow.NLeftUpVDepthNGCount_J},{PublicSet.Datashow.NRightUpVAngleNGCount_J},{PublicSet.Datashow.NRightUpVWidthNGCount_J},{PublicSet.Datashow.NRightUpVDepthNGCount_J},{PublicSet.Datashow.NLeftDownVAngleNGCount_J},{PublicSet.Datashow.NLeftDownVWidthNGCount_J},{PublicSet.Datashow.NLeftDownVDepthNGCount_J},{PublicSet.Datashow.NRightDownVAngleNGCount_J},{PublicSet.Datashow.NRightDownVWidthNGCount_J},{PublicSet.Datashow.NRightDownVDepthNGCount_J},{PublicSet.Datashow.NMeasureLineNGCount_J}";
                FileStream fs = new FileStream(TJ_NG_WeiJuanN, FileMode.Append, FileAccess.Write);
                sw = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                sw.WriteLine(data);
                fs.Flush(); sw.Close(); fs.Close();
            }
            else
            {
                data = $"{str},{PublicSet.Datashow.PSum_J},{PublicSet.Datashow.PSumNG_J},{PublicSet.Datashow.PNGOne_J},{PublicSet.Datashow.PNGTwo_J},{PublicSet.Datashow.PNGThree_J},{PublicSet.Datashow.PJPHeadLengthNGCount_J},{PublicSet.Datashow.PJPTailLengthNGCount_J},{PublicSet.Datashow.PJPHeadWidthNGCount_J},{PublicSet.Datashow.PJPTailWidthNGCount_J},{PublicSet.Datashow.PJELeftShoulderNGCount_J},{PublicSet.Datashow.PJERightShoulderNGCount_J},{PublicSet.Datashow.PJEWidthNGCount_J},{PublicSet.Datashow.PJEHeightNGCount_J},{PublicSet.Datashow.PCeramicsHeightNGCount_J},{PublicSet.Datashow.PJeOddmentsNGCount_J},{PublicSet.Datashow.PJeBevelLimitNGCount_J},{PublicSet.Datashow.PJPCoatingNGCount_J},{PublicSet.Datashow.PJPTotalWidthNGCount_J},{PublicSet.Datashow.PLeftUpAngleNGCount_J},{PublicSet.Datashow.PRightUpAngleNGCount_J},{PublicSet.Datashow.PLeftDownAngleNGCount_J},{PublicSet.Datashow.PRightDownAngleNGCount_J},{PublicSet.Datashow.PLeftUpBevelNGCount_J},{PublicSet.Datashow.PRightUpBevelNGCount_J},{PublicSet.Datashow.PLeftDownBevelNGCount_J},{PublicSet.Datashow.PRightDownBevelNGCount_J},{PublicSet.Datashow.PLeftUpVAngleNGCount_J},{PublicSet.Datashow.PLeftUpVWidthNGCount_J},{PublicSet.Datashow.PLeftUpVDepthNGCount_J},{PublicSet.Datashow.PRightUpVAngleNGCount_J},{PublicSet.Datashow.PRightUpVWidthNGCount_J},{PublicSet.Datashow.PRightUpVDepthNGCount_J},{PublicSet.Datashow.PLeftDownVAngleNGCount_J},{PublicSet.Datashow.PLeftDownVWidthNGCount_J},{PublicSet.Datashow.PLeftDownVDepthNGCount_J},{PublicSet.Datashow.PRightDownVAngleNGCount_J},{PublicSet.Datashow.PRightDownVWidthNGCount_J},{PublicSet.Datashow.PRightDownVDepthNGCount_J},{PublicSet.Datashow.PMeasureLineNGCount_J}";
                FileStream fs = new FileStream(TJ_NG_WeiJuanP, FileMode.Append, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                sw.WriteLine(data);
                fs.Flush();
                sw.Close(); fs.Close();
            }
        }

        /// <summary>
        /// 写CSV统计数据NG每极卷
        /// </summary>
        /// <param name="str"></param>
        /// <param name="Od"></param>
        public static void WriteCsv_TJ_NG_WeiJuan(string str, JPOffsetData od)
        {
            //表头BoxHead ="日期,线体编号,设备编号,正负极,班次,开始时间,截至时间,极片总数,极片NG数,极片头长,极片尾长,极片头宽,极片尾宽,左肩宽,右肩宽,极耳宽,极耳高,陶瓷高/带料高,极耳余料，极耳打折,涂布高,极片总长,左上垂直度,右上垂直度,左下垂直度,右下垂直度,左上缺角,右上缺角,左下缺角,右下缺角,左上V角度,左上V宽度,左上V深度,右上V角度,右上V宽度,右上V深度,左下V角度,左下V宽度,左下V深度,右下V角度,右下V宽度,右下V深度,找边失败，极片偏移－X最大,极片偏移－X最小,极片偏移－X平均,极片偏移－X标准差,极片偏移－Y最大,极片偏移－Y最小,极片偏移－Y平均,极片偏移－Y标准差,极片偏移－Z最大,极片偏移－Z最小,极片偏移－Z平均,极片偏移－Z标准差";
            string data;
            if (str.Contains("负极"))
            {
                data = $"{str},{od.Sum},{od.SumNG},{od.One},{od.Two},{od.Three},{od.JPHeadLengthNG},{od.JPTailLengthNG},{od.JPHeadWidthNG},{od.JPTailWidthNG},{od.JELeftShoulderNG},{od.JERightShoulderNG},{od.JEWidthNG},{od.JEHeightNG},{od.DLHeightOrCeramicsNG},{od.JEOddmentsNG},{od.JEBevelLimitNG},{od.JPCoatingNG},{od.JPTotalWidthNG},{od.LeftUpAngleNG},{od.RightUpAngleNG},{od.LeftDownAngleNG},{od.RightDownAngleNG},{od.LeftUpBevelNG},{od.RightUpBevelNG},{od.LeftDownBevelNG},{od.RightDownBevelNG},{od.LeftUpVAngleNG},{od.LeftUpVWidthNG},{od.LeftUpVDepthNG},{od.RightUpVAngleNG},{od.RightUpVWidthNG},{od.RightUpVDepthNG},{od.LeftDownVAngleNG},{od.LeftDownVWidthNG},{od.LeftDownVDepthNG},{od.RightDownVAngleNG},{od.RightDownVWidthNG},{od.RightDownVDepthNG},{od.MeasureLineNG}";
                FileStream fs = new FileStream(TJ_NG_WeiJuanN, FileMode.Append, FileAccess.Write);
                sw = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                sw.WriteLine(data);
                fs.Flush(); sw.Close(); fs.Close();
            }
            else
            {
                data = $"{str},{od.Sum},{od.SumNG},{od.One},{od.Two},{od.Three},{od.JPHeadLengthNG},{od.JPTailLengthNG},{od.JPHeadWidthNG},{od.JPTailWidthNG},{od.JELeftShoulderNG},{od.JERightShoulderNG},{od.JEWidthNG},{od.JEHeightNG},{od.DLHeightOrCeramicsNG},{od.JEOddmentsNG},{od.JEBevelLimitNG},{od.JPCoatingNG},{od.JPTotalWidthNG},{od.LeftUpAngleNG},{od.RightUpAngleNG},{od.LeftDownAngleNG},{od.RightDownAngleNG},{od.LeftUpBevelNG},{od.RightUpBevelNG},{od.LeftDownBevelNG},{od.RightDownBevelNG},{od.LeftUpVAngleNG},{od.LeftUpVWidthNG},{od.LeftUpVDepthNG},{od.RightUpVAngleNG},{od.RightUpVWidthNG},{od.RightUpVDepthNG},{od.LeftDownVAngleNG},{od.LeftDownVWidthNG},{od.LeftDownVDepthNG},{od.RightDownVAngleNG},{od.RightDownVWidthNG},{od.RightDownVDepthNG},{od.MeasureLineNG}";
                FileStream fs = new FileStream(TJ_NG_WeiJuanP, FileMode.Append, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                sw.WriteLine(data);
                fs.Flush();
                sw.Close(); fs.Close();
            }
        }



        /// <summary>
        /// 写CSV统计数据NG每班次优先级
        /// </summary>
        /// <param name="str"></param>
        /// <param name="Od"></param>
        public static void WriteCsv_TJ_NG_BanCi_Priority(string str, JPOffsetData Od)
        {
            try
            {
                //表头BoxHead ="日期,线体编号,设备编号,正负极,班次,开始时间,截至时间,极片总数,极片NG数,极片头长,极片尾长,极片头宽,极片尾宽,左肩宽,右肩宽,极耳宽,极耳高,陶瓷高/带料高,极耳余料，极耳打折,涂布高,极片总长,左上垂直度,右上垂直度,左下垂直度,右下垂直度,左上缺角,右上缺角,左下缺角,右下缺角,左上V角度,左上V宽度,左上V深度,右上V角度,右上V宽度,右上V深度,左下V角度,左下V宽度,左下V深度,右下V角度,右下V宽度,右下V深度,找边失败，极片偏移－X最大,极片偏移－X最小,极片偏移－X平均,极片偏移－X标准差,极片偏移－Y最大,极片偏移－Y最小,极片偏移－Y平均,极片偏移－Y标准差,极片偏移－Z最大,极片偏移－Z最小,极片偏移－Z平均,极片偏移－Z标准差";
                string data = $"{str},{Od.Sum},{Od.SumNG},{Od.One},{Od.Two},{Od.Three},{Od.JPHeadLengthNG},{Od.JPTailLengthNG},{Od.JPHeadWidthNG},{Od.JPTailWidthNG},{Od.JELeftShoulderNG},{Od.JERightShoulderNG},{Od.JEWidthNG},{Od.JEHeightNG},{Od.DLHeightOrCeramicsNG},{Od.JEOddmentsNG},{Od.JEBevelLimitNG},{Od.JPCoatingNG},{Od.JPTotalWidthNG},{Od.LeftUpAngleNG},{Od.RightUpAngleNG},{Od.LeftDownAngleNG},{Od.RightDownAngleNG},{Od.LeftUpBevelNG},{Od.RightUpBevelNG},{Od.LeftDownBevelNG},{Od.RightDownBevelNG},{Od.LeftUpVAngleNG},{Od.LeftUpVWidthNG},{Od.LeftUpVDepthNG},{Od.RightUpVAngleNG},{Od.RightUpVWidthNG},{Od.RightUpVDepthNG},{Od.LeftDownVAngleNG},{Od.LeftDownVWidthNG},{Od.LeftDownVDepthNG},{Od.RightDownVAngleNG},{Od.RightDownVWidthNG},{Od.RightDownVDepthNG},{Od.MeasureLineNG},{Od.XMax},{Od.XMin},{Od.XAvg.ToString("0.000")},{Od.XSta.ToString("0.000")},{Od.YMax},{Od.YMin},{Od.YAvg.ToString("0.000")},{Od.YSta},{Od.ZMax.ToString("0.000")},{Od.ZMin},{Od.ZAvg.ToString("0.000")},{Od.ZSta.ToString("0.000")}";
                if (str.Contains("负极"))
                {
                    FileStream fs = new FileStream(TJ_NG_BanCiN_Priority, FileMode.Append, FileAccess.Write);
                    sw = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                    sw.WriteLine(data);
                    fs.Flush(); sw.Close(); fs.Close();
                }
                else
                {
                    FileStream fs = new FileStream(TJ_NG_BanCiP_Priority, FileMode.Append, FileAccess.Write);
                    StreamWriter sw = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                    sw.WriteLine(data);
                    fs.Flush();
                    sw.Close(); fs.Close();
                }
            }
            catch (Exception ex)
            {
                Tool.LogForm("表格被占用" + ex.ToString());
            }


        }

        static bool flag;
        public static StreamWriter SW_P, SW_N;
        static bool flagN = true, flagP = true;
        /// <summary>
        /// 写CSV统计数据NG每小时统计（分时统计）
        /// </summary>
        /// <param name="str"></param>
        /// <param name="Od"></param>
        public static void WriteCsv_TJ_Hour_Priority(string NOrP, string starttime1, string stoptime2)
        {
            //string BoxHeadN_Hour = "日期,时间段,极片头宽,极片尾宽,极耳宽,极耳高,极片长,料区长度,极耳到边距离,上膜宽,极耳打折,极耳余料,V角尺寸异常,V角余料,角度异常,其他";         
            try
            {
                #region 分时统计
                try
                {
                    if (PublicSet.Myset.TJ_Hour)
                    {
                        string Morn = Convert.ToDateTime(PublicSet.Myset.Morn).AddMinutes(1).ToString("HH:mm");
                        string Night = Convert.ToDateTime(PublicSet.Myset.Night).AddMinutes(1).ToString("HH:mm");


                        int MorningResult = DateTime.Compare(DateTime.Now, Convert.ToDateTime(Morn));
                        int NightResult = DateTime.Compare(DateTime.Now, Convert.ToDateTime(Night));
                        string MornOrNight = "";
                        DateTime dateTime = new DateTime();
                        if (MorningResult == -1 && NightResult == -1)//凌晨时间为前一天夜班
                        {
                            dateTime = DateTime.Now.AddDays(-1);
                            MornOrNight = "晚班";
                        }
                        if (MorningResult == 1 && NightResult == 1 || NightResult == 0)//当天夜班并非凌晨
                        {
                            dateTime = DateTime.Now;
                            MornOrNight = "晚班";
                        }
                        if ((MorningResult == 1 && NightResult == -1) || MorningResult == 0)//当天白班
                        {
                            MornOrNight = "白班"; dateTime = DateTime.Now;
                        }


                        if (!flag)//刚开启软件时生成得表格
                        {
                            flag = true;
                            TJ_NG_HourP_Priority = Replace_TJ_Hour(PublicSet.Myset.TJDataSava, dateTime, "", "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "\\分时统计\\" + Replace("yyyy-MM-dd Line-MachineNorPWS", MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + ".csv";
                            TJ_NG_HourN_Priority = Replace_TJ_Hour(PublicSet.Myset.TJDataSava, dateTime, "", "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "\\分时统计\\" + Replace("yyyy-MM-dd Line-MachineNorPWS", MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + ".csv";
                            //生成文件夹
                            if (!Directory.Exists(Replace(PublicSet.Myset.TJDataSava, "", "", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "\\分时统计"))
                            {
                                Directory.CreateDirectory(Replace(PublicSet.Myset.TJDataSava, "", "", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "\\分时统计");
                            }

                            if (!File.Exists(TJ_NG_HourN_Priority))
                            {

                                string BoxHead = "日期,时间段,极片宽度,极片长度,极耳高度,极耳宽度,极耳翻折/破损,V角深度,V角底宽,极耳到边距离,极耳余料,V角余料,角度NG,上膜宽宽度,抓边失败,其他,NG总数,OK总数,检测总数";
                                //string BoxHead = "日期,时间段,极片头宽,极片尾宽,极耳宽,极耳高,极片长,料区长度,极耳到边距离,上膜宽,极耳翻折,极耳余料,V角尺寸异常,V角余料,角度异常,其他,NG总数,OK总数,检测总数";
                                FileStream fs = new FileStream(TJ_NG_HourN_Priority, FileMode.Create, FileAccess.Write);
                                StreamWriter sw1 = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                                sw1.WriteLine(BoxHead);
                                sw1.Flush();
                                sw1.Close();
                                fs.Close();
                                fs.Dispose(); flagN = true;

                            }
                            if (!File.Exists(TJ_NG_HourP_Priority))
                            {
                                string BoxHead = "日期,时间段,极片宽度,极片总长,极耳高度,极耳宽度,极耳翻折/破损,V角深度,V角底宽,极耳到边距离,极耳余料,V角余料,角度NG,陶瓷层宽度,抓边失败,料区长度,其他,NG总数,OK总数,检测总数";
                                //string BoxHead = "日期,时间段,极片头宽,极片尾宽,极耳宽,极耳高,极片长,料区长度,极耳到边距离,AT9宽度,极耳翻折,极耳余料,V角尺寸异常,V角余料,角度异常,其他,NG总数,OK总数,检测总数";
                                FileStream fs = new FileStream(TJ_NG_HourP_Priority, FileMode.Create, FileAccess.Write);
                                StreamWriter sw1 = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                                sw1.WriteLine(BoxHead);
                                sw1.Flush();
                                sw1.Close();
                                fs.Close();
                                fs.Dispose(); flagP = true;
                            }
                            try
                            {
                                if (flagN)
                                {
                                    SW_N = new StreamWriter(TJ_NG_HourN_Priority, true, Encoding.GetEncoding("gb2312")); flagN = false;
                                }
                                if (flagP)
                                {
                                    SW_P = new StreamWriter(TJ_NG_HourP_Priority, true, Encoding.GetEncoding("gb2312")); flagP = false;
                                }

                            }
                            catch (Exception)
                            {
                                Tool.LogForm("分时统计数据表格被占用,数据丢失");
                               MessageBox.Show("分时统计数据表格被占用,请关闭表格，并重启软件。否则数据将无法存储");
                            }
                        }

                        if (NOrP.Contains("负极"))
                        {
                            //string BoxHead = "日期,时间段,极片宽度,极片长度,极耳高度,极耳宽度,极耳翻折/破损,V角深度,V角底宽,极耳到边距离,极耳余料,V角余料,角度NG,上膜宽宽度,抓边失败,其他,NG总数,OK总数,检测总数";
                            string data = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},{starttime1}-{stoptime2},{PublicSet.Datashow.NJPHeadWidthNGCount_P},{PublicSet.Datashow.NJPHeadLengthNGCount_P},{PublicSet.Datashow.NJEHeightNGCount_P},{PublicSet.Datashow.NJEWidthNGCount_P},{PublicSet.Datashow.NJeBevelLimitNGCount_P},{PublicSet.Datashow.NVDepthNGCount_P},{PublicSet.Datashow.NVWidthNGCount_P},{PublicSet.Datashow.NJELeftShoulderNGCount_P},{PublicSet.Datashow.NJeOddmentsNGCount_P},{PublicSet.Datashow.NJeOddmentsNGCount_P},{PublicSet.Datashow.NBevelNGCount_P},{PublicSet.Datashow.NAngleNGCount_P},{PublicSet.Datashow.NDLHeightNGCount_P},{PublicSet.Datashow.NMeasureLineNGCount_P},0,{PublicSet.Datashow.NSumNG_P},{PublicSet.Datashow.NSum_P - PublicSet.Datashow.NSumNG_P},{PublicSet.Datashow.NSum_P}";
                            //FileStream fs = new FileStream(TJ_NG_HourN_Priority, FileMode.Append, FileAccess.Write);
                            //sw = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                            SW_N.WriteLine(data);
                            SW_N.Flush();/* sw.Close(); fs.Close();*/
                        }
                        else
                        {
                            //string BoxHead = "日期,时间段,极片宽度,极片总长,极耳高度,极耳宽度,极耳翻折/破损,V角深度,V角底宽,极耳到边距离,极耳余料,V角余料,角度NG,陶瓷层宽度,抓边失败,料区长度,其他,NG总数,OK总数,检测总数";
                            string data = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},{starttime1}-{stoptime2},{PublicSet.Datashow.PJPHeadWidthNGCount_P},{PublicSet.Datashow.PJPHeadLengthNGCount_P},{PublicSet.Datashow.PJEHeightNGCount_P},{PublicSet.Datashow.PJEWidthNGCount_P},{PublicSet.Datashow.PJeBevelLimitNGCount_P},{PublicSet.Datashow.PVDepthNGCount_P},{PublicSet.Datashow.PVWidthNGCount_P},{PublicSet.Datashow.PJERightShoulderNGCount_P},{PublicSet.Datashow.PJeOddmentsNGCount_P},{PublicSet.Datashow.PBevelNGCount_P},{PublicSet.Datashow.PAngleNGCount_P},{PublicSet.Datashow.PCeramicHeightNGCount_P},{PublicSet.Datashow.PMeasureLineNGCount_P},{PublicSet.Datashow.PJPCoatingNGCount_P},0,{PublicSet.Datashow.PSumNG_P},{PublicSet.Datashow.PSum_P - PublicSet.Datashow.PSumNG_P},{PublicSet.Datashow.PSum_P}";
                            //FileStream fs = new FileStream(TJ_NG_HourP_Priority, FileMode.Append, FileAccess.Write);
                            //StreamWriter sw = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                            SW_P.WriteLine(data);
                            SW_P.Flush();
                            //sw.Close(); fs.Close();
                        }

                        string time = DateTime.Now.AddMinutes(1).ToString("HH:mm");
                        if (time == Morn || time == Night)//软件在正常开启时，到点生成新的表格
                        {

                            Morn = Convert.ToDateTime(PublicSet.Myset.Morn).AddMinutes(1).ToString("HH:mm");
                            Night = Convert.ToDateTime(PublicSet.Myset.Night).AddMinutes(1).ToString("HH:mm");


                            MorningResult = DateTime.Compare(DateTime.Now.AddMinutes(1), Convert.ToDateTime(Morn));
                            NightResult = DateTime.Compare(DateTime.Now.AddMinutes(1), Convert.ToDateTime(Night));
                            MornOrNight = "";
                            dateTime = new DateTime().AddMinutes(1);
                            if (MorningResult == -1 && NightResult == -1)//凌晨时间为前一天夜班
                            {
                                dateTime = DateTime.Now.AddDays(-1);
                                MornOrNight = "晚班";
                            }
                            if (MorningResult == 1 && NightResult == 1 || NightResult == 0)//当天夜班并非凌晨
                            {
                                dateTime = DateTime.Now;
                                MornOrNight = "晚班";
                            }
                            if ((MorningResult == 1 && NightResult == -1) || MorningResult == 0)//当天白班
                            {
                                MornOrNight = "白班"; dateTime = DateTime.Now;
                            }

                            if (NOrP.Contains("正极")) TJ_NG_HourP_Priority = Replace_TJ_Hour(PublicSet.Myset.TJDataSava, dateTime, "", "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "\\分时统计\\" + Replace("yyyy-MM-dd Line-MachineNorPWS", MornOrNight, "正极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + ".csv";
                            if (NOrP.Contains("负极")) TJ_NG_HourN_Priority = Replace_TJ_Hour(PublicSet.Myset.TJDataSava, dateTime, "", "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "\\分时统计\\" + Replace("yyyy-MM-dd Line-MachineNorPWS", MornOrNight, "负极", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + ".csv";

                            //生成文件夹
                            if (!Directory.Exists(Replace(PublicSet.Myset.TJDataSava, "", "", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "\\分时统计"))
                            {
                                Directory.CreateDirectory(Replace(PublicSet.Myset.TJDataSava, "", "", PublicSet.Cameraset.LineID, PublicSet.Cameraset.MachineID) + "\\分时统计");
                            }

                            if (!File.Exists(TJ_NG_HourN_Priority))
                            {
                                string BoxHead = "日期,时间段,极片宽度,极片长度,极耳高度,极耳宽度,极耳翻折/破损,V角深度,V角底宽,极耳到边距离,极耳余料,V角余料,角度NG,上膜宽宽度,抓边失败,其他,NG总数,OK总数,检测总数";
                                FileStream fs = new FileStream(TJ_NG_HourN_Priority, FileMode.Create, FileAccess.Write);
                                StreamWriter sw1 = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                                sw1.WriteLine(BoxHead);
                                sw1.Flush();
                                sw1.Close();
                                fs.Close();
                                fs.Dispose(); flagN = true;

                            }
                            if (!File.Exists(TJ_NG_HourP_Priority))
                            {
                                string BoxHead = "日期,时间段,极片宽度,极片总长,极耳高度,极耳宽度,极耳翻折/破损,V角深度,V角底宽,极耳到边距离,极耳余料,V角余料,角度NG,陶瓷层宽度,抓边失败,料区长度,其他,NG总数,OK总数,检测总数";
                                FileStream fs = new FileStream(TJ_NG_HourP_Priority, FileMode.Create, FileAccess.Write);
                                StreamWriter sw1 = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                                sw1.WriteLine(BoxHead);
                                sw1.Flush();
                                sw1.Close();
                                fs.Close();
                                fs.Dispose(); flagP = true;
                            }
                            try
                            {
                                if (flagN)
                                {
                                    SW_N = new StreamWriter(TJ_NG_HourN_Priority, true, Encoding.GetEncoding("gb2312")); flagN = false;
                                }
                                if (flagP)
                                {
                                    SW_P = new StreamWriter(TJ_NG_HourP_Priority, true, Encoding.GetEncoding("gb2312")); flagP = false;
                                }

                            }
                            catch (Exception)
                            {
                                Tool.LogForm("分时统计数据表格被占用,数据丢失");                               
                                MessageBox.Show("分时统计数据表格被占用,请关闭表格，并重启软件。否则数据将无法存储");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                }
                #endregion


                #region NPOI写入表格方法 (已取消)
                ////打开文件
                //FileStream file2003 = new FileStream(TJ_NG_HourN_Priority, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                //HSSFWorkbook workbook2003 = new HSSFWorkbook(file2003);
                ////获取工作表命名为Sheet1的
                //HSSFSheet SheetOne = (HSSFSheet)workbook2003.GetSheet("Sheet1");

                ////当第一次写入时更新写入时间
                //if (PublicSet.Datashow.NStarttime_Hour1 == null) PublicSet.Datashow.NStarttime_Hour1 = DateTime.Now.ToString("HH");
                ////当时间更新为下一个小时的时候将数据的写入行数+1并更新写入时间
                //if (PublicSet.Datashow.NStarttime_Hour1 != DateTime.Now.ToString("HH"))
                //{
                //    PublicSet.Datashow.NStarttime_Hour1 = DateTime.Now.ToString("HH");
                //    PublicSet.Myset.countN++;
                //    #region 负极每小时清零一次NG数
                //    PublicSet.Datashow.NJPHeadWidthNGCount_P = 0;
                //    PublicSet.Datashow.NJPTailWidthNGCount_P = 0;
                //    PublicSet.Datashow.NJPHeadLengthNGCount_P = 0;
                //    PublicSet.Datashow.NJEWidthNGCount_P = 0;
                //    PublicSet.Datashow.NJEHeightNGCount_P = 0;
                //    PublicSet.Myset.NJEShoulderNGCount_P = 0;
                //    PublicSet.Myset.NJEShoulderNGCount_P = 0;
                //    PublicSet.Datashow.NDLHeightNGCount_P = 0;
                //    PublicSet.Datashow.NJeBevelLimitNGCount_P = 0;
                //    PublicSet.Datashow.NVNGCount_P = 0;
                //    PublicSet.Datashow.NBevelNGCount_P = 0;
                //    PublicSet.Datashow.NAngleNGCount_P = 0;
                //    PublicSet.Datashow.NMeasureLineNGCount_P = 0;
                //    #endregion
                //}
                ////在Sheet1工作表创建指定的行
                //SheetOne.CreateRow(PublicSet.Myset.countN);
                ////获取Sheet1工作表的行
                //HSSFRow SheetRow = (HSSFRow)SheetOne.GetRow(PublicSet.Myset.countN);
                ////对获取到的工作表的行创建单元格
                //HSSFCell[] SheetCell = new HSSFCell[16];
                //for (int i = 0; i < 16; i++)
                //{
                //    //开始创建单元格（根据表头的数量创建单元格的数量）
                //    SheetCell[i] = (HSSFCell)SheetRow.CreateCell(i);
                //}
                ////单元格创建完毕后进行赋值
                //SheetCell[0].SetCellValue(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//日期
                //SheetCell[1].SetCellValue(DateTime.Now.ToString("HH:00") + "-" + DateTime.Now.AddHours(1).ToString("HH:00"));//时间段
                //SheetCell[2].SetCellValue(PublicSet.Datashow.NJPHeadWidthNGCount_P.ToString());//极片头宽
                //SheetCell[3].SetCellValue(PublicSet.Datashow.NJPTailWidthNGCount_P.ToString());//极片尾宽
                //SheetCell[4].SetCellValue(PublicSet.Datashow.NJEWidthNGCount_P.ToString());//极耳宽
                //SheetCell[5].SetCellValue(PublicSet.Datashow.NJEWidthNGCount_P.ToString());//极耳高
                //SheetCell[6].SetCellValue(PublicSet.Datashow.NJPHeadLengthNGCount_P.ToString());//极片长
                //SheetCell[7].SetCellValue(PublicSet.Datashow.NJPCoatingNGCount_P.ToString());//料区长度
                //SheetCell[8].SetCellValue(PublicSet.Myset.NJEShoulderNGCount_P.ToString());//极耳到边距离
                //SheetCell[9].SetCellValue(PublicSet.Datashow.NDLHeightNGCount_P.ToString());//上膜宽
                //SheetCell[10].SetCellValue(PublicSet.Datashow.NJeBevelLimitNGCount_P.ToString());//极耳打折
                //SheetCell[11].SetCellValue("0");//极耳余料
                //SheetCell[12].SetCellValue(PublicSet.Datashow.NVNGCount_P.ToString());//V角尺寸异常
                //SheetCell[13].SetCellValue(PublicSet.Datashow.NBevelNGCount_P.ToString());//V角余料
                //SheetCell[14].SetCellValue(PublicSet.Datashow.NAngleNGCount_P.ToString());//角度异常
                //SheetCell[15].SetCellValue(PublicSet.Datashow.NMeasureLineNGCount_P.ToString());//其他
                ////开始写入数据
                //file2003 = new FileStream(TJ_NG_HourN_Priority, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                //workbook2003.Write(file2003);
                //file2003.Close();
                //workbook2003.Close();

                #endregion

            }
            catch (Exception ex)
            {
                Tool.LogForm(ex.ToString());
            }
        }



        /// <summary>
        ///  写CSV片位数据每百片
        /// </summary>
        /// <param name="str"></param>
        /// <param name="Od"></param>
        public static void WriteCsv_PW_Hundred(string str, JPOffsetData Od)
        {
            //  表头BoxHead = "日期,线体编号,设备编号,工位,正负极,班次,片位是否调整,开始时间,截止时间,极片偏移-皮带方向最大,极片偏移-皮带方向最小,极片偏移-皮带方向平均,极片偏移-皮带方向标准差,极片偏移-非皮带方向最大,极片偏移-非皮带方向最小,极片偏移-非皮带方向平均,极片偏移-非皮带方向标准差,极片偏移-Z最大,极片偏移-Z最小,极片偏移-Z平均,极片偏移-Z标准差";

            string data = $"{str},{Od.StartTime.ToString("yyyy-MM-dd HH:mm:ss")},{Od.StopTime.ToString("yyyy-MM-dd HH:mm:ss")},{Od.XMax},{Od.XMin},{Od.XAvg.ToString("0.000")},{Od.XSta.ToString("0.000")},{Od.YMax},{Od.YMin},{Od.YAvg.ToString("0.000")},{Od.YSta.ToString("0.000")},{Od.ZMax},{Od.ZMin},{Od.ZAvg.ToString("0.000")},{Od.ZSta.ToString("0.000")}";
            if (str.Contains("负极"))
            {
                FileStream fs = new FileStream(PW_NG_BaiPianN, FileMode.Append, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                sw.WriteLine(data);
                fs.Flush();
                sw.Close();
                fs.Close();
            }
            else
            {
                FileStream fs = new FileStream(PW_NG_BaiPianP, FileMode.Append, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                sw.WriteLine(data);
                fs.Flush();
                sw.Close();
                fs.Close();
            }
        }

        #endregion

        /// <summary>
        /// 图像缩或放大
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void HMouseWheel(MouseEventArgs e, HWindow hw, HObject image)
        {
            HTuple Zoom, Row, Col, Button;
            HTuple Row0, Column0, Row00, Column00, Ht, Wt, r1, c1, r2, c2;
            if (e.Delta > 0)
            {
                Zoom = 1.5;
            }
            else
            {
                Zoom = 0.5;
            }
            HOperatorSet.GetMposition(hw, out Row, out Col, out Button);
            HOperatorSet.GetPart(hw, out Row0, out Column0, out Row00, out Column00);
            Ht = Row00 - Row0;
            Wt = Column00 - Column0;
            if (Ht * Wt < 32000 * 32000 || Zoom == 1.5)//普通版halcon能处理的图像最大尺寸是32K*32K。如果无限缩小原图像，导致显示的图像超出限制，则会造成程序崩溃。这也是当时3C项目上，窗体抗不住操的原因
            {
                r1 = (Row0 + ((1 - (1.0 / Zoom)) * (Row - Row0)));
                c1 = (Column0 + ((1 - (1.0 / Zoom)) * (Col - Column0)));
                r2 = r1 + (Ht / Zoom);
                c2 = c1 + (Wt / Zoom);
                HOperatorSet.SetPart(hw, r1, c1, r2, c2);
                HOperatorSet.ClearWindow(hw);
                HOperatorSet.DispObj(image, hw);
            }
        }

        static int count = 0;
        public static bool IsEventArgs;//鼠标是否按下
        public static double RowDown;//鼠标按下时的行坐标 
        public static double ColDown;//鼠标按下时的列坐标
        /// <summary>
        /// 图像移动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void Picture_Move(HWindow hw, HObject image, HTuple Row, HTuple Column)
        {
            if (IsEventArgs)
            {
                ++count;
                if (count == 5)//忽略微小移动
                {
                    HTuple row1, col1, row2, col2;
                    // HOperatorSet.GetMposition(hw, out Row, out Column, out _);
                    double RowMove = Row - RowDown;   //鼠标弹起时的行坐标减去按下时的行坐标，得到行坐标的移动值
                    double ColMove = Column - ColDown;//鼠标弹起时的列坐标减去按下时的列坐标，得到列坐标的移动值
                    HOperatorSet.GetPart(hw, out row1, out col1, out row2, out col2);//得到当前的窗口坐标
                    HOperatorSet.SetPart(hw, row1 - RowMove, col1 - ColMove, row2 - RowMove, col2 - ColMove);//这里可能有些不好理解。以左上角原点为参考点       

                    hw.ClearWindow();
                    HOperatorSet.DispObj(image, hw);
                    count = 0;
                }
            }
        }


        #region 窗体缩放

        /// <summary>
        /// 根据窗体尺寸变化调整控件位置和尺寸
        /// </summary>
        /// <param name="form">窗体</param>
        public static void SetState(Form form)
        {
            if (form.Tag == null)
            {
                return;
            }
            string[] states = form.Tag.ToString().Split(',');
            double scaleX = form.Width / double.Parse(states[0]);
            double scaleY = form.Height / double.Parse(states[1]);
            foreach (Control control in form.Controls)
            {
                SetSize(control, scaleX, scaleY);
            }
        }

        /// <summary>
        /// 记录控件的位置和大小到Tag属性
        /// </summary>
        /// <param name="control">控件</param>
        public static void SetTag(Control control)
        {
            //control.Tag = $"{control.Left + control.Width / 2},{control.Top + control.Height / 2},{control.Width},{control.Height},{control.Font.Size}";
            control.Tag = $"{control.Left},{control.Top},{control.Width},{control.Height},{control.Font.Size}";
            foreach (Control controlSon in control.Controls)
            {
                SetTag(controlSon);
            }
        }



        /// <summary>
        /// 根据控件大小变化调整子控件的位置和大小
        /// </summary>
        /// <param name="control">控件</param>
        public static void SetSize(Control control)
        {
            if (control.Tag == null)
            {
                return;
            }
            string[] size = control.Tag.ToString().Split(',');
            double scaleX = control.Width / double.Parse(size[2]);
            double scaleY = control.Height / double.Parse(size[3]);
            SetSize(control, scaleX, scaleY);
        }

        /// <summary>
        /// 按给定缩放比例调整控件位置和尺寸
        /// </summary>
        /// <param name="control">控件</param>
        /// <param name="scaleX">横向缩放比例</param>
        /// <param name="scaleY">竖向缩放比例</param>
        public static void SetState(Control control, double scaleX, double scaleY)
        {
            foreach (Control controlSon in control.Controls)
            {
                SetState(controlSon, scaleX, scaleY);
            }
            string[] states = control.Tag.ToString().Split(',');
            double width = int.Parse(states[2]) * scaleX, height = int.Parse(states[3]) * scaleY;
            control.Left = (int)(int.Parse(states[0]) * scaleX - width / 2);
            control.Top = (int)(int.Parse(states[1]) * scaleY - height / 2);
            control.Width = (int)width;
            control.Height = (int)height;
            control.Font = new Font(control.Font.Name, (float)(float.Parse(states[4]) * Math.Min(scaleX, scaleY)));
        }


        /// <summary>
        /// 按给定缩放比例调整子控件的位置和大小
        /// </summary>
        /// <param name="control">控件</param>
        /// <param name="scaleX">横向缩放比例</param>
        /// <param name="scaleY">竖向缩放比例</param>
        private static void SetSize(Control control, double scaleX, double scaleY)
        {
            foreach (Control controlSon in control.Controls)
            {
                if (controlSon.Tag != null)
                {
                    string[] size = controlSon.Tag.ToString().Split(',');
                    //double width = int.Parse(size[2]) * scaleX, height = int.Parse(size[3]) * scaleY;
                    //control.Left = (int)(int.Parse(size[0]) * scaleX - width / 2);
                    //control.Top = (int)(int.Parse(size[1]) * scaleY - height / 2);
                    //control.Width = (int)width;
                    //control.Height = (int)height;
                    controlSon.Left = (int)(int.Parse(size[0]) * scaleX);
                    controlSon.Top = (int)(int.Parse(size[1]) * scaleY);
                    controlSon.Width = (int)(int.Parse(size[2]) * scaleX);
                    controlSon.Height = (int)(int.Parse(size[3]) * scaleY);
                    //control.Font = new Font(control.Font.Name, (float)(float.Parse(size[4]) * Math.Min(scaleX, scaleY)));
                }
                SetSize(controlSon, scaleX, scaleY);
            }
        }
        #endregion



        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="filepath"></param>
        [DllImport("mysql.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public static extern void encryption(string filepath);
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="filepath"></param>
        [DllImport("mysql.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public static extern void decrypt(string filepath);
        /// <summary>
        /// 字符串编码格式转换
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string toUTF8(string data)
        {
            //string s = data.Replace("\\", "/");
            byte[] encodedBytes = Encoding.UTF8.GetBytes(data.Replace("\\", "/"));
            Console.Write(encodedBytes);
            IntPtr pBuffer = Marshal.AllocHGlobal(encodedBytes.Length);
            Marshal.Copy(encodedBytes, 0, pBuffer, encodedBytes.Length);
            Encoding fromEcoding = Encoding.GetEncoding("UTF-8");
            return fromEcoding.GetString(encodedBytes);
        }



    }
    sealed class AllowAllAssemblyVersionsDeserializationBinder : SerializationBinder
    {
        public override Type BindToType(string assemblyName, string typeName)
        {
            return Type.GetType($"{typeName}, {Assembly.GetExecutingAssembly().FullName}");
        }
    }
}
